【问题标题】:MVC Validation message internationalizationMVC 验证消息国际化
【发布时间】:2013-02-05 14:04:43
【问题描述】:

例如,我希望这个默认的 ASP.NET MVC 4 验证消息:The value 'qsdqsdqs' is not valid for Montant 以法语显示。

我找到了这个包http://nuget.org/packages/Microsoft.AspNet.Mvc.fr/ 并安装了它,但我该如何让它工作呢?

我在 web.config 中添加了<globalization culture="fr-FR" uiCulture="auto:fr" /> 并引用了 dll,但消息仍然是英文的

【问题讨论】:

  • 我找到了答案:正确的语法是
  • 实际上它在验证数字属性时有效,但在使用 'RequiredAttribute' 时无效:/

标签: c# validation asp.net-mvc-4 internationalization


【解决方案1】:

首先,您应该像这样将消息保存在资源文件中:

Resources/ErrorMessages.resx // default messages
Resources/ErrorMessages.fr.resx // for french 

在服务器端,这很容易,您可以通过向模型添加属性来实现。这样做:

[Required(ErrorMessageResourceType = typeof(Resources.ErrorMessages), ErrorMessageResourceName = "FieldRequired")]

其中 "FieldRequired"Resources.ErrorMessages

中的字段之一

棘手的部分是您希望客户端验证也能正常工作。比您必须创建自己的属性类,该类扩展 属性之一并且还实现 IClientValidatable

你就是这样:

public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
    {
        public override string FormatErrorMessage(string name)
        {
            return String.Format(ErrorMessages.FieldRequired, name);
        } 

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRequiredRule(String.Format(ErrorMessages.FieldRequired, metadata.DisplayName));
            return new[] { rule };
        }
    }

从现在开始,您将在模型中使用 CustomRequired 而不是 Required。您也不必每次都指定消息。

编辑

现在我看到了您对 SynerCoder 答案的评论 - 您不想自己翻译消息。好吧,我认为这不是正确的方法。即使您找到可以为您翻译标准消息的内容,它也不会翻译任何自定义消息,因此您最终可能会混合使用两种方法。这通常会导致你不知道如何咬的魔法错误。我强烈建议您自己进行翻译(这并不多 - 大约 20 个?)。好处是没有意外错误的灵活解决方案。

【讨论】:

  • 我在 MVC 5 解决方案中使用了提供的解决方案,该解决方案使用自定义生成的 ResourceProvider(从表中生成的强类型),并且还翻译了客户端验证消息(似乎不需要 IClientValidatable 技巧)。谢谢。
【解决方案2】:

实际使用 ResX Manager。 Visual Studio 菜单工具 -> 扩展和更新 -> 在在线工具中搜索“resx”。

通过它的助手,我的所有字符串都可以像“Res.SomeTranslatedString”一样访问。 现在感谢以上所有人,让我们翻译一个布尔属性的注册视图模型消息,以检查用户是否接受了条款和条件。使用上述工具,我将字符串放入Res.YouMustAcceptTermsAndConditions。然后我们修改viewmodel代码:

曾经:

public class RegisterViewModel
{
    [Required]
    [Range(typeof(bool), "true", "true", ErrorMessage = "You must accept terms and conditions.")]
    [Display(Name = "Agree to terms.")]
    public bool AgreeTerms { get; set; }

成为:

public class RegisterViewModel
{
    [Required]
    [Range(typeof(bool), "true", "true", ErrorMessageResourceType = typeof(Res), ErrorMessageResourceName = "YouMustAcceptTermsAndConditions")]
    [Display(Name = "Agree to terms.")]
    public bool AgreeTerms { get; set; }

现在您看到我们的 [Display] 仍未翻译。解决方案在这里:https://stackoverflow.com/a/3877154/7149454

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多