首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MVC 4忽略DefaultModelBinder.ResourceClassKey

MVC 4忽略DefaultModelBinder.ResourceClassKey
EN

Stack Overflow用户
提问于 2012-09-22 15:38:29
回答 1查看 7.1K关注 0票数 23

使用App_GlobalResources键向PropertyValueRequired添加资源文件并将DefaultModelBinder.ResourceClassKey更改为文件名对MVC 4没有影响。字符串The {0} field is required从未更改过。我不想在每个必需的字段上设置资源类类型和键。我是不是遗漏了什么?

编辑:

我对达林·季米特洛夫的代码做了一个小小的修改,以保证所需的自定义工作:

代码语言:javascript
复制
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";
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-22 17:17:32

这并不是特定于ASP.NET MVC 4,在ASP.NET MVC 3中也是如此,您不能使用DefaultModelBinder.ResourceClassKey来设置所需的消息,只能使用PropertyValueInvalid

实现您正在寻找的目标的一种方法是定义自定义RequiredAttributeAdapter

代码语言:javascript
复制
public class MyRequiredAttributeAdapter : RequiredAttributeAdapter
{
    public MyRequiredAttributeAdapter(
        ModelMetadata metadata,
        ControllerContext context,
        RequiredAttribute attribute
    ) : base(metadata, context, attribute)
    {
        attribute.ErrorMessageResourceType = typeof(Messages);
        attribute.ErrorMessageResourceName = "PropertyValueRequired";
    }
}

您将在Application_Start中注册

代码语言:javascript
复制
DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(RequiredAttribute),
    typeof(MyRequiredAttributeAdapter)
);

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

票数 41
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12545176

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档