数据注释属性在MVC应用程序中使用好友类的元数据无法正常工作 [英] Data annotation attributes not working using buddy class metadata in an MVC app

查看:101
本文介绍了数据注释属性在MVC应用程序中使用好友类的元数据无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现暗示,MVC 2识别属性元数据,其中数据注解属性应用于一个搭档元数据类的伙伴类的类型,和那哥们级的实际实体类分MetadataType,如下面。然而,如下,似乎使得所呈现的用户界面的任何差异是 DisplayName的的唯一属性。为什么像数据类型必需的其他属性只读不工作?即为什么我能进入在只读字段中的文本?为什么我不能当一个必填字段为空,得到一个错误?为什么数据类型属性都没有明显的效果?为什么 EditorForModel 不包括验证消息?

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; }
    }
}

我找到的行为同样我是否使用一个明确的 LabelFor TextBoxFor 每个模型属性,或单 EditorForModel 为整个模型。

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.

推荐答案

由于我包括在我看来,一个 EnableClientValidation()通话时,我希望这些属性的原因客户端,将要执行的Javascript验证,以及要显示的验证消息

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.

事实证明,仅仅包括 EnableClientValidation()不单单不够的,人们也有权修改母版页(或视图,如果你不使用主页),包括以下脚本:

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>

我不知道jQuery的需要验证或没有,但我把它作为建议,事情现在正常工作。

I'm not sure the jQuery is required for validation or not, but I included it as advised and things work properly now.

这篇关于数据注释属性在MVC应用程序中使用好友类的元数据无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆