ASP.NET Core: How to localize Html.ValidationMessage?

时间:2017-05-16 09:34:04

标签: asp.net asp.net-mvc razor asp.net-core localization

I use the following snippet in my .cshtml file:

@Html.ValidationMessage("loginError")

And this in my Controller:

ModelState.AddModelError("loginError", message);

Now I want to localize the message inside my View (not in the controller).

For standard text I use this:

@Localizer["Login"]

How do I localize the ValidationMessage? Can I get the raw message from it and just give it to my Localizer or is there a better way?

2 个答案:

答案 0 :(得分:0)

好的,这是我的建议,但它非常黑客:

@Localizer[@ViewData.ModelState["loginError"]?.Errors[0].ErrorMessage ?? ""]

在我的View中使用此功能。但我愿意接受更好的解决方案......

答案 1 :(得分:0)

我想我找到了一个更好的解决方案:

  1. 注入IStringLocalizerFactory factory
  2. 创建本地化程序:_localizer = factory.Create(typeof(LoginModel));
  3. ModelState.AddModelError(" loginError",message);
  4. 将消息存储在包含特定于模型类型的验证消息的资源文件中。