c# - 自定义错误消息未在 ASP.NET MVC 4 中翻译

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

我想翻译验证信息“The field Date must be a date.”

我在 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?

最佳答案

我将解释我如何指定客户端消息。首先,在您设置资源的模型中:

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

其次,在覆盖线程文化的 Controller 中,我从路由中获取它,例如在 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 ... 没有别的,它对我很有效。我希望这种方法对您有所帮助。

关于c# - 自定义错误消息未在 ASP.NET MVC 4 中翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26890014/

相关文章:

c# - 从下拉列表中选择一种类型的模型以填充 ASP.NET MVC 中另一个模型的属性

c# - 从 ContentControl 中的按钮触发命令?

C#:垃圾收集器

jquery - 当前上下文 MVC 中不存在名称 'button'

asp.net-mvc - 使用 Web 部署发布 ASP.NET MVC2 站点

c# - 如何使用 Jquery Mobile 在 MVC 中动态创建带有 Count Bubbles 的链接

c# - 拥有一个类的多个实例(引用类型)是否使其线程安全?

c# - MvcOptions.InputFormatters 不适用于 asp.net vnext beta7

c# - 可以从 javascript/jquery 获取返回 url 吗?

c# - 为什么我的自定义 DisplayFor 模板实际上没有在此处呈现?