Complex Data Validation using Data Annotations
I have the following class
public partial class Contact
{
public Contact()
{
}
#region Primitive Properties
public virtual int Id { get; set; }
[Display(ResourceType = typeof(Common), Name = "Person_Name")]
[Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(Common))]
[StringLength(100, ErrorMessageResourceName = "Incorrect_Field_Length",
ErrorMessageResourceType = typeof(Common))]
public virtual string Name { get; set; }
[Display(ResourceType = typeof(Common), Name = "Telephone_Number")]
[DataType(DataType.PhoneNumber)]
[StringLength(100, ErrorMessageResourceName = "Incorrect_Field_Length",
ErrorMessageResourceType = typeof(Common))]
[Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(Common))]
public virtual string Telephone { get; set; }
[Display(ResourceType = typeof(Common), Name = "EmailAddress")]
[DataType(DataType.EmailAddress)]
[StringLength(255, ErrorMessageResourceName = "Incorrect_Field_Length",
ErrorMessageResourceType = typeof(Common))]
[Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(Common))]
public virtual string Email { get; set; }
[Display(ResourceType = typeof(Common), Name = "ContactType")]
public virtual ContactType ContactType { get; set; }
public virtual Company Company { get; set; }
#endregion
}
The ContactType looks like this
public partial class ContactType
{
#region Primitive Properties
public virtual int Id { get; set; }
[Display(ResourceType = typeof(Common), Name = "ContactType_Name")]
[StringLength(50, ErrorMessageResourceName = "Incorrect_Field_Length",
ErrorMessageResourceType = typeof(Common))]
[Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(Common))]
public virtual string Name { get; set; }
#endregion
}
The problem I have is that when I edit the Contact object, ModelState.IsValid is always false. This is due to the Name within the ContactType being Null, it has the correct id. This is because the ContactType is selected by a dropdown selection. I don't want to remove the validation from ContactType as it is needed when adding new ContactType objects. Any idea how I can get around this issue?
Please shout if I need to provide mo开发者_如何学编程re information.
Cheers
When you validate Contact, you shouldn't validate the ContactType property as that property will never be properly send by the user. Validating a ContactTypeId of int type property should solve this issue and leave you ContactType validation intact.
I'm not sure what data access framework you are using (looks like EF Code First) but in EF Model First you can activate the generation of foreign-key properties on top of the usual navigation properties which makes add/edit scenarios much easier (specially in the web where you only pass values and not full objects).
精彩评论