微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

将资源文件添加到具有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。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐