I am using .NET 4.0 and the entity framework to do some server side validation. I have a simple table called "Contacts" which looks like this:
ID int Dont Allow Nulls
FirstName nvarchar(50) Dont Allow Nulls SecondName nvarchar(50) Dont Allow Nulls MobileNumber nvarchar(50) Dont Allow Nulls HomeNumber nvarchar(50) Allow NullsI have a ContactController and a strongly typed view of type Contact which displays the edit textboxes. When I click "Create" to try and create a new Contact I have a Controller Method as below:
[HttpPost]
public ActionResult Create(Contact contact)
{
if (ModelState.IsValid)
{
ContactService.CreateContact(contact);
RedirectToAction("Index");
}
return View();
}
If I press the button without entering anything my code breaks before it gets to here. The error comes in the Contacts.Designer.cs at this line:
_FirstName = StructuralObject.SetValidValue(value, false);
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String FirstName
{
get
{
return _FirstName;
}
set
{
OnFirstNameChanging(value);
ReportPropertyChanging("FirstName");
_FirstName = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("FirstName");
OnFirstNameChanged();
}
}
This is a ConstraintException and it says this property cannot b开发者_运维知识库e set to a null value. If I set the fields to all accept null values then the code works and this error doesnt happen and the Model is checked to see if it is valid like expected. What is going wrong here please??
Thanks
Here is the solution. I had to add
[DisplayFormat(ConvertEmptyStringToNull = false)]
annotation to the field not allowing nulls. There is a full explanation of this error here.
[MetadataType(typeof(Contact_Validate))]
public partial class Contact
{
public string FullName()
{
return _FirstName + " " + _SecondName;
}
}
public class Contact_Validate
{
[Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string FirstName { get; set; }
[Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string SecondName { get; set; }
[Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string MobileNumber { get; set; }
public string HomeNumber { get; set; }
}
精彩评论