找到你要的答案

Q:ASP.Net MVC Validation Localization Not Overriding Browser Default Language

Q:ASP。NET MVC验证定位不是压倒一切的浏览器默认语言

I have localization working as expected for labels, but cannot seem to figure out why the validation messages are not being localized. If I change my browser default language to "es-ES", the validation messages are in Spanish. But, the application should be using the language set in our local database. For example, in the code below, the label for Impacts is being localized to Spanish, but the ProductID error message is displaying in English. The Culture is being set at the beginning of the controller action using a cookie.

I also noticed if I set the language to Spanish in the web.config that the validation messages are in Spanish.

Here is the current code that works correctly for the label, but not for the validation message.

What I want is for the validation error message to be in Spanish like the label.

Web.Config:

<globalization culture="auto" uiCulture="auto" enableClientBasedCulture="true" />

View Model:

[Required(ErrorMessageResourceName = "errProduct", ErrorMessageResourceType = typeof(Resources.ProductSupport.addcallText))]
public Int32? ProductID { get; set; }

[Display(Name = "lblEffect", ResourceType = typeof(Resources.ProductSupport.addcallText))]
public IEnumerable<SelectListItem> Impacts { get; set; }

View:

@Html.ValidationMessageFor(x => x.ProductID)

@Html.LabelFor(x => x.Impacts)

我有本地化的工作预期的标签,但似乎无法找出为什么验证消息不被本地化。如果我将浏览器默认语言改为“ES”,则验证消息为西班牙语。但是,应用程序应该使用本地数据库中的语言集。例如,在以下代码中,对影响标签被定位于西班牙,但ProductID错误消息显示英文。使用cookie将控制器设置在控制器动作的开始处。

我还注意到,如果我把语言西班牙语在Web.config,验证消息在西班牙。

这里是对标签正确运行的当前代码,但不是验证消息。

我想要的是验证错误消息是在西班牙像标签。

网页配置:

<globalization culture="auto" uiCulture="auto" enableClientBasedCulture="true" />

视图模型:

[Required(ErrorMessageResourceName = "errProduct", ErrorMessageResourceType = typeof(Resources.ProductSupport.addcallText))]
public Int32? ProductID { get; set; }

[Display(Name = "lblEffect", ResourceType = typeof(Resources.ProductSupport.addcallText))]
public IEnumerable<SelectListItem> Impacts { get; set; }

观:

@Html.ValidationMessageFor(x => x.ProductID)

@Html.LabelFor(x => x.Impacts)
answer1: 回答1:

Setting the culture in the Global.asax.cs file seems to be working.

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    LanguageHelper.SetCulture(null);
}

在Global.asax.cs文件设置的文化似乎是工作。

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    LanguageHelper.SetCulture(null);
}
c#  asp.net-mvc  localization  .net-4.5