问题描述
我在ASP.NET MVC3创建这样一个继承的属性:
公共密封类RequiredFromResourceAttribute:RequiredAttribute标签
{
公共RequiredFromResourceAttribute(字符串errorResourceName,串errorResourceTypeName)
{
this.ErrorMessageResourceName = errorResourceName;
this.ErrorMessageResourceType = Type.GetType(errorResourceTypeName);
}
}
和使用这样的:
[RequiredFromResource(标题,Resources.Resource,MyProject.Mvc,版本= 1.0.0.0,文化=中立,公钥=空)]
公共字符串名称{搞定;组; }
它没有工作和MVC忽略了它。然后,我创建一个刚从继承RequiredAttribute标签这样一个简单的类:
公共类MyRequiredAttribute:RequiredAttribute标签
{
}
我用它就像我说的。但它没有再工作。
虽然,所有这些方面的DisplayNameAtrribute很好地工作。
这是什么问题?
您可以通过在Global.asax中加入以下code解决这个问题:(找到答案的)
<$p$p><$c$c>DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredLocalizableAttribute), typeof运算(RequiredAttributeAdapter));另外,使用marcind的解决方案,我发现, ModelClientValidationRequiredRule
的构造函数需要一个错误信息。这里是更新的版本,其包括用于该字段的显示名称
公开的IEnumerable&LT; ModelClientValidationRule&GT; GetClientValidationRules(ModelMetadata元,ControllerContext上下文)
{
弦乐味精= FormatErrorMessage(metadata.GetDisplayName());
产量返回新ModelClientValidationRequiredRule(MSG);
}
I created an inherited attribute like this in ASP.NET MVC3:
public sealed class RequiredFromResourceAttribute : RequiredAttribute
{
public RequiredFromResourceAttribute(string errorResourceName, string errorResourceTypeName)
{
this.ErrorMessageResourceName = errorResourceName;
this.ErrorMessageResourceType = Type.GetType(errorResourceTypeName);
}
}
And use it like this:
[RequiredFromResource("Title", "Resources.Resource, MyProject.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")]
public string Title { get; set; }
It didn't work and the MVC ignored it. Then I create a simpler class which just inherited from RequiredAttribute like this:
public class MyRequiredAttribute : RequiredAttribute
{
}
I use it like that I said. But it didn't work again.
Although, all these ways work on "DisplayNameAtrribute" perfectly.
What is the problem?
You can fix this by adding the following code in Global.asax: (found the answer here)
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredLocalizableAttribute), typeof(RequiredAttributeAdapter));
Alternatively, using marcind's solution, I found that the constructor for ModelClientValidationRequiredRule
requires an error message. Here is an updated version that includes the display name for the field:
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
string msg = FormatErrorMessage(metadata.GetDisplayName());
yield return new ModelClientValidationRequiredRule(msg);
}
这篇关于在ASP.NET MVC 3 RequiredAttribute标签从时inherting客户端验证不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!