ASP.NET MVC中数据注释的默认资源
发布时间:2020-12-16 00:39:38 所属栏目:asp.Net 来源:网络整理
导读:有一种方法可以将默认资源设置为数据注释验证? 我不想这样做: [Required(ErrorMessage="Name required.",ErrorMessageResourceType=typeof(CustomDataAnnotationsResources)]public string Name { get; set; } 我想要这样的东西: Global.asax中 DataAnnot
有一种方法可以将默认资源设置为数据注释验证?
我不想这样做: [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 – 将输入值传递给Action(ASP.Net MVC 3)
- asp.net – 在Web API Formatter中设置Expires / Caching标
- asp.net – ASP.MVC CORE网站的最大上传大小
- asp.net – 多久我应该打开/关闭我的Booksleeve连接?
- ASP.NET等价的服务器端包括
- .net – 如何搜索以我的plaftform为目标的Nuget包?
- asp.net mvc CodeFirst模式数据库迁移步骤详解
- asp.net – 通过javascript从代码后面访问变量
- asp.net-mvc-3 – 在控制器操作完成后使用Javascript隐藏图
- asp.net-mvc-3 – 另一个数据库实例RavenDB MVC3已经使用的
推荐文章
站长推荐
- asp.net web api定义的b/s调用方法一例
- asp.net – SqlConnection localhost用户名失败
- asp.net-membership – 用于创建.Net成员资格提供
- .net – SqlDataSource与ObjectDataSource
- 如何在asp.net webforms捆绑中将cdN添加到bundle
- asp.net – ReportViewer控件和Ajax UpdatePanel
- asp.net单文件带进度条上传的解决方案
- asp.net-mvc – 为什么IIS没有清理池回收导致网站
- 如何使用ASP.NET Identity 3.0没有Entity Framew
- 如何在使用ASP.NET MVC的jQuery AJAX调用中触发“
热点阅读