I have found hints that MVC 2 recognises the ‘buddy class’ type of property metadata, where data annotation attributes are applied to a ‘buddy’ metadata class, and the MetadataType on the actual entity class points to that buddy class, as below. However, as below, it seems the only attribute that makes any difference to the rendered UI is DisplayName. Why are the other attributes like DataType, Required, and ReadOnly not working? I.e. why can I enter text in a read only field? Why do I not get an error when a required field is empty? Why does the DataType attribute have no apparent effect? Why does EditorForModel not include validation messages?
[MetadataType(typeof(CustomerMetadata))]
public partial class Customer
{
public class CustomerMetadata
{
[ScaffoldColumn(false)]
public object CustomerId { get; set; }
[DisplayName("CustomerNo.")]
[ReadOnly(true)]
[Required(AllowEmptyStrings = false, ErrorMessage = "Customer No. is required.")]
public object CustomerNo { get; set; }
}
}
I find behaviour the same whether I use an explicit LabelFor and TextBoxFor for each model property, or a single EditorForModel for the whole model.
Because I was including an
EnableClientValidation()call in my view, I was expecting these attributes to cause client side, Javascript validation to be performed, and validation messages to be displayed.It turns out that merely including
EnableClientValidation()is not alone enough, and one also has to modify the master page (or view if you’re not using a master page), to include the following scripts:I’m not sure the jQuery is required for validation or not, but I included it as advised and things work properly now.