Data annotation attributes not working using buddy class metadata in an MVC app

微笑、不失礼 提交于 2019-12-25 04:54:18

问题


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.


回答1:


  1. Required only affects validation.
  2. Readonly only affects binding.

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




回答2:


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:

<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 the jQuery is required for validation or not, but I included it as advised and things work properly now.



来源:https://stackoverflow.com/questions/3882501/data-annotation-attributes-not-working-using-buddy-class-metadata-in-an-mvc-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!