Data annotation attributes not working using friend class metadata in an MVC application

I found hints that MVC 2 recognizes the metadata of the properties of the buddy type class, where the data annotation attributes are applied to the buddy metadata class, and the metadata type in the actual object class points to this buddy class, as below. However, as shown below, it seems that the only attribute that has any meaning for the rendered interface is DisplayName . Why don't other attributes like DataType , Required and ReadOnly work? That is why I can enter text in a read-only field? Why am I not getting an error when the required field is empty? Why does the DataType attribute have no visible effect? Why EditorForModel n't EditorForModel contain 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 consider the behavior the same if I use explicit LabelFor and TextBoxFor for each property of the model or one EditorForModel for the whole model.

0
source share
2 answers

Since I included the EnableClientValidation() call in my view, I expected these attributes to call the client side, Javascript validation, and execution of validation messages to be displayed.

It turns out that just turning on EnableClientValidation() alone is not enough, and you also need to change the main page (or view if you are not using the main page) to include the following scripts:

 <script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script> 

I'm not sure if jQuery is required for validation or not, but I turned it on as advised, and now everything works correctly.

0
source
  • Required only affects validation.
  • Readonly only affects binding.

The ErrorMessage string is only output when using the ValidationFor() method.

+2
source

All Articles