ASP.NET MVC中数据注释的默认资源
发布时间:2020-05-23 15:50:58 所属栏目:asp.Net 来源:互联网
导读:有一种方法可以将默认资源设置为数据注释验证? 我不想这样做: [Required(ErrorMessage=Name required., ErrorMessageResourceType=typeof(CustomDataAnnotationsResources)]public string Name { get; set; } 我想要这样的东西: Global.asax中 DataAnn
|
有一种方法可以将默认资源设置为数据注释验证? 我不想这样做: [Required(ErrorMessage="Name required.",ErrorMessageResourceType=typeof(CustomDataAnnotationsResources)]
public string Name { get; set; }
我想要这样的东西: Global.asax中 DataAnnotations.DefaultResources = typeof(CustomDataAnnotationsResources); 然后 [Required]
public string Name { get; set; }
有人给我一个光! 提前致谢 编辑 我的真正问题是EF Code First CTP4。 CTP5修复它。感谢大家 解决方法你可以尝试这样做:将此类添加到项目中的某个地方: public class ExternalResourceDataAnnotationsValidator : DataAnnotationsModelValidator<ValidationAttribute>
{
/// <summary>
/// The type of the resource which holds the error messqages
/// </summary>
public static Type ResourceType { get; set; }
/// <summary>
/// Function to get the ErrorMessageResourceName from the Attribute
/// </summary>
public static Func<ValidationAttribute,string> ResourceNameFunc
{
get { return _resourceNameFunc; }
set { _resourceNameFunc = value; }
}
private static Func<ValidationAttribute,string> _resourceNameFunc = attr => attr.GetType().Name;
public ExternalResourceDataAnnotationsValidator(ModelMetadata metadata,ControllerContext context,ValidationAttribute attribute)
: base(metadata,context,attribute)
{
if (Attribute.ErrorMessageResourceType == null)
{
this.Attribute.ErrorMessageResourceType = ResourceType;
}
if (Attribute.ErrorMessageResourceName == null)
{
this.Attribute.ErrorMessageResourceName = ResourceNameFunc(this.Attribute);
}
}
}
并在global.asax中添加以下内容: // Add once ExternalResourceDataAnnotationsValidator.ResourceType = typeof(CustomDataAnnotationsResources); // Add one line for every attribute you want their ErrorMessageResourceType replaced. DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RangeAttribute),typeof(ExternalResourceDataAnnotationsValidator)); 它将查找与错误消息的验证器类型相同名称的属性。您可以通过ResourceNameFunc属性更改它。 编辑:AFAIK这是从MVC2起的作品,因为DataAnnotationsModelValidatorProvider是在MVC2中引入的。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc-3 – 自定义ActionInvoker与MVC 3中ActionFilt
- 从.NET开始 – ASP.NET,WPF,Silverlight或命令行C#?
- asp.net-mvc-4 – visual studio 2012 RC无法加载类型Syste
- asp.net-mvc – ASP.NET MVC:如何创建一个可用的UrlHelper
- asp.net-mvc – ASP.NET MVC术语让我沮丧 – 为什么’ViewM
- asp.net – 我可以在MasterPage中使用UpdatePanel来包装嵌套
- asp.net-mvc – HiddenFor(x = x.Id)正在由UrlParameter而不
- asp.net – 将设置移动到另一个配置文件
- ASP.NET MVC – MapRoute与routes.Add(和404s)
- 如何在ASP.NET页面上使用框架?
推荐文章
站长推荐
热点阅读
