我想翻译验证信息“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);
}
资源格式正确很重要:ModelBinders.resx、ModelBinders.es-ES.resx、ModelBinders.en-US.resx ... 没有别的,它对我很有效。我希望这种方法对您有所帮助。
关于c# - 自定义错误消息未在 ASP.NET MVC 4 中翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26890014/