在 MVC 应用程序中使用伙伴类元数据时,数据注释属性不起作用
我发现 MVC 2 可以识别“伙伴类”类型的属性元数据,其中数据注释属性应用于“伙伴”元数据类,并且实际实体类上的 MetadataType 指向该伙伴类,如下所示。然而,如下所示,对呈现的 UI 产生任何影响的唯一属性似乎是 DisplayName
。为什么 DataType
、Required
和 ReadOnly
等其他属性不起作用?即为什么我可以在只读字段中输入文本?当必填字段为空时,为什么我不会收到错误消息?为什么DataType属性没有明显效果?为什么 EditorForModel
不包含验证消息?
[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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
必需
仅影响验证。Readonly
仅影响绑定。仅当您使用
ValidationFor()
方法时才会输出ErrorMessage
字符串。Required
only affects validation.Readonly
only affects binding.The
ErrorMessage
string is only output when you use theValidationFor()
method.因为我在视图中包含了一个
EnableClientValidation()
调用,所以我期望这些属性会导致客户端执行 Javascript 验证并显示验证消息。事实证明,仅包含
EnableClientValidation()
还不够,还必须修改母版页(如果不使用母版页,则查看),以包含以下脚本:我不确定验证是否需要 jQuery,但我按照建议将其包含在内,现在一切正常。
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.