【问题标题】:MVC 4 ignores DefaultModelBinder.ResourceClassKeyMVC 4 忽略 DefaultModelBinder.ResourceClassKey
【发布时间】:2012-09-14 17:46:45
【问题描述】:

使用PropertyValueRequired 键将资源文件添加到App_GlobalResources 并将DefaultModelBinder.ResourceClassKey 更改为文件名对MVC 4 没有影响。字符串The {0} field is required 永远不会更改。 我不想在每个必填字段上设置资源类类型和键。 我错过了什么吗?

编辑:

我对 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 localization asp.net-mvc-4 model-binding


    【解决方案1】:

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

    实现您所寻找的一种方法是定义一个自定义RequiredAttributeAdapter

    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注册:

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

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

    【讨论】:

    • 完美!我做了很多研究,没有发现类似的东西。非常感谢。
    • 是否可以为类型验证做类似的事情,例如日期?
    • 我们研究了为什么您需要一个适配器:GlobalResources.PropertyValueRequired 条目仅用于未标记为“必需”的不可空类型。 “真正的”Required 消息只能使用此适配器解决方案进行更改。
    • 存在 DataTypeAttributeAdapterCompareAttributeAdapter 但与 RequiredAttributeAdapter 不同的是,它们是内部的。什么鬼?
    • 很好的答案!我将添加 resx 文件不必位于 App_GlobalResources 文件夹中。它根本不必位于同一个项目中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多