Csharp/C#教程:全局覆盖ASP.Net MVC默认属性错误消息分享


全局覆盖ASP.Net MVC默认属性错误消息

如何使用来自不同程序集的资源来覆盖MVC5应用程序中的默认属性错误消息?

我的网站是命名空间:Company.Web

我的资源程序集是命名空间:Company.Web.Resources

我可以使用以下方法单独本地化属性错误消息:

[Required(ErrorMessageResourceName = "PropertyValueRequired", ErrorMessageResourceType = typeof(Company.Web.Resources.Messages))] 

但是,由于我们的错误消息始终为“必需”,因此我只想放置[Required]属性而无需指定资源名称。 我还想覆盖MVC输出的默认数据类型消息,这是通过属性无法完成的。

字段{0}必须是日期。

我想成为

失效日期

我已经看到了一些示例,您可以将资源文件放在App_GlobalResources中(使用键PropertyValueRequiredFieldMustBeDateFieldMustBeNumeric )并设置ClientDataTypeModelValidatorProvider.ResourceClassKey ,但我已经有了一个我想要使用的外部资源程序集。

我尝试在我的Global.asax中使用以下内容而没有运气:

 ClientDataTypeModelValidatorProvider.ResourceClassKey = "Company.Web.Resources.Messages" 

我怎么能做到这一点? 有任何想法吗?

更新(部分解决)

我可以简单地通过创建新的validation适配器并使用它们来代替默认值来解决基于属性的问题:

 public class MyRequiredAttributeAdapter : RequiredAttributeAdapter { public MyRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute) : base(metadata, context, attribute) { if (attribute.ErrorMessage.IsNullOrWhitespace() && attribute.ErrorMessageResourceName.IsNullOrWhitespace() && attribute.ErrorMessageResourceType == null) { attribute.ErrorMessageResourceType = typeof (Resources.Validation.Messages); attribute.ErrorMessageResourceName = "PropertyValueRequired"; } } } 

Global.asax中

 DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(MyRequiredAttributeAdapter)); 

但是,这仍然让我不知道如何覆盖非null属性(如DateTime和int)的默认数据类型消息。 此外,我相信有一些我无法覆盖,因为它们是内部的(DataTypeAttributeAdapter,CompareAttributeAdapter)。

这可能很晚,但是这里的解决方案应该主要基于部分解决方案背后的逻辑。

  1. 为您的项目实现自定义RequiredAttribute

     public class MyRequiredAttribute : RequiredAttribute { //Your custom code } 
  2. 修改您的MyRequiredAttributeAdapter代码,如图所示。 请注意,您现在需要从通用DataAnnotationsModelValidator类inheritance,该类允许您传入自定义MyRequiredAttribute

     public class MyRequiredAttributeAdapter : DataAnnotationsModelValidator { public MyRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, MyRequiredAttribute attribute) : base(metadata, context, attribute) { if (string.IsNullOrWhiteSpace(attribute.ErrorMessage) && string.IsNullOrWhiteSpace(attribute.ErrorMessageResourceName) && attribute.ErrorMessageResourceType == null) { attribute.ErrorMessageResourceType = typeof(Resources.Validation.Messages); attribute.ErrorMessageResourceName = "PropertyValueRequired"; } } } 
  3. 将其添加到Global.asax(根据您在部分解决方案中的内容进行修改)

    上述就是C#学习教程:全局覆盖ASP.Net MVC默认属性错误消息分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

     DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(MyRequiredAttributeAdapter)); 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1019664.html

(0)
上一篇 2022年1月5日
下一篇 2022年1月5日

精彩推荐