ASP.NET核心:如何本地化Html.ValidationMessage?

时间:2022-11-01 04:12:45

I use the following snippet in my .cshtml file:

我在.cshtml文件中使用以下代码段:

@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).

现在我想在我的View中本地化消息(不在控制器中)。

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?

如何本地化ValidationMessage?我可以从中获取原始消息并将其提供给我的Localizer或者有更好的方法吗?

2 个解决方案

#1


0  

Ok here's my suggestion but it's quite a hack:

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

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

Using this inside my View works. But I'm open to better solutions...

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

#2


0  

I think i have found a better solution:

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

  1. Inject IStringLocalizerFactory factory
  2. 注入IStringLocalizerFactory工厂

  3. Create localizer: _localizer = factory.Create(typeof(LoginModel));
  4. 创建定位器:_localizer = factory.Create(typeof(LoginModel));

  5. ModelState.AddModelError("loginError", message);

Store the message in resource file that contains model type specific validation messages.

将消息存储在包含特定于模型类型的验证消息的资源文件中。

#1


0  

Ok here's my suggestion but it's quite a hack:

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

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

Using this inside my View works. But I'm open to better solutions...

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

#2


0  

I think i have found a better solution:

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

  1. Inject IStringLocalizerFactory factory
  2. 注入IStringLocalizerFactory工厂

  3. Create localizer: _localizer = factory.Create(typeof(LoginModel));
  4. 创建定位器:_localizer = factory.Create(typeof(LoginModel));

  5. ModelState.AddModelError("loginError", message);

Store the message in resource file that contains model type specific validation messages.

将消息存储在包含特定于模型类型的验证消息的资源文件中。