ASP.NET MVC 4中未翻译自定义的错误消息

时间:2014-11-12 15:02:26

标签: c# asp.net-mvc asp.net-mvc-4 localization global-asax

我想翻译验证讯息"字段日期必须是日期。"

我已将以下密钥添加到Global.asax

的Application_Start()中
ClientDataTypeModelValidatorProvider.ResourceClassKey = "ModelBinders";
DefaultModelBinder.ResourceClassKey = "ModelBinders";

我在App_GlobalResources中创建了ModelBinders.resx,ModelBinders.nl.resx,ModelBinders.fr.resx。

我在.resx文件中添加了以下字符串资源(或翻译):

Name                   Value
====                   =====
FieldMustBeDate        The field {0} must be a date.
FieldMustBeNumeric     The field {0} must be a number.
PropertyValueInvalid   The value '{0}' is not valid for {1}.
PropertyValueRequired  A value is required.

当我提交日期字符串时,我会收到" FieldMustBeDate"的翻译。当我提交无效日期时(例如" 01/01 / 201a"),我收到" PropertyValueInvalid"的未翻译消息。这是在默认的ModelBinders.resx中定义的,而不是翻译...如何为PropertyValueInvalid显示正确的翻译?

1 个答案:

答案 0 :(得分:9)

我将解释具体的客户端消息。首先,在模型中设置资源:

    [Required(ErrorMessageResourceType = typeof(Resources.ModelBinders), ErrorMessageResourceName = "Required")]
    [Display(Name = "UserName", ResourceType = typeof(Resources.ModelBinders))]
    public string UserName { get; set; }

其次,在控制器中你覆盖了线程文化,我从一个路径中得到了它,例如在Initialize方法中:

    protected override void Initialize(RequestContext requestContext)
    {
        string cultureInfo = requestContext.RouteData.GetRequiredString("cultureInfo");
        System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(cultureInfo);
        System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(cultureInfo);
        base.Initialize(requestContext);
    }

Client messages in English

Client messages in Spanish

资源格式正确非常重要:ModelBinders.resx,ModelBinders.es-ES.resx,ModelBinders.en-US.resx ......别的,它对我很有用。我希望这种方法对你有帮助。