加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – MVC 4忽略DefaultModelBinder.ResourceClassKey

发布时间:2020-12-15 18:32:54 所属栏目:asp.Net 来源:网络整理
导读:将资源文件添加到具有PropertyValueRequired键的App_GlobalResources中,并将DefaultModelBinder.ResourceClassKey更改为文件名对MVC 4没有影响。字符串{0}字段是必需的,从未更改。 我不想在每个必填字段上设置资源类类型和密钥。 我错过了什么吗? 编辑:
将资源文件添加到具有PropertyValueRequired键的App_GlobalResources中,并将DefaultModelBinder.ResourceClassKey更改为文件名对MVC 4没有影响。字符串{0}字段是必需的,从未更改。
我不想在每个必填字段上设置资源类类型和密钥。
我错过了什么吗?

编辑:

我对Darin Dimitrov的代码做了一个小的修改,以保持“必需”的自定义工作:

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

解决方法

这不是特定于ASP.NET MVC 4.它在ASP.NET MVC 3中是一样的。您不能使用DefaultModelBinder.ResourceClassKey设置所需的消息,只能使用PropertyValueInvalid。

实现您要查找的一种方法是定义一个自定义的RequiredAttributeAdapter:

public class MyRequiredAttributeAdapter : RequiredAttributeAdapter
{
    public MyRequiredAttributeAdapter(
        ModelMetadata metadata,RequiredAttribute attribute
    ) : base(metadata,attribute)
    {
        attribute.ErrorMessageResourceType = typeof(Messages);
        attribute.ErrorMessageResourceName = "PropertyValueRequired";
    }
}

您将在Application_Start中注册:

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

现在当一个不可为空的字段未分配一个值时,错误消息将来自Messages.PropertyValueRequired,其中必须在App_GlobalResources中定义Messages.resx。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读