【问题标题】:Customised error messages are not translated in ASP.NET MVC 4在 ASP.NET MVC 4 中未翻译自定义错误消息
【发布时间】:2014-11-12 15:02:26
【问题描述】:

我想翻译验证消息“日期字段必须是日期。”

我在 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”)时,我收到默认 ModelBinders.resx 中定义的“PropertyValueInvalid”的未翻译消息,而不是翻译...如何显示正确的翻译对于 PropertyValueInvalid?

【问题讨论】:

  • 你可以发布你的模型吗?

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


【解决方案1】:

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

    [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);
    }

资源格式正确很重要:ModelBinders.resx、ModelBinders.es-ES.resx、ModelBinders.en-US.resx ... 仅此而已,它对我很有效。我希望这种方法对您有所帮助。

【讨论】:

  • 谢谢!我做了同样的事情,但没有覆盖控制器的初始化方法。添加该代码使其对我有用。
  • 确保不要将用于设置线程语言的代码添加到动作过滤器的 OnActionExecuting 方法中 - 它不会起作用!
猜你喜欢
  • 1970-01-01
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 2021-02-10
  • 2011-09-23
  • 2015-09-21
相关资源
最近更新 更多