我在asp net mvc 5应用程序中遇到了验证消息本地化的问题。
我用它进行本地化:
路线配置:
[Internationalization]
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("DefaultLocalized",
"{language}-{culture}/{controller}/{action}/{id}",
new
{
controller = "Home",
action = "Index",
id = "",
language = "de",
culture = "DE"
});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
LocalizationAttribute:
class InternationalizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string language = (string)filterContext.RouteData.Values["language"] ?? "de";
string culture = (string)filterContext.RouteData.Values["culture"] ?? "DE";
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));
}
}
模型属性示例:
[Display(Order = 0, ResourceType = typeof(resourceProjectName.ApplicationStrings), Name = "LabelText")] // this works
[Required(ErrorMessageResourceType = typeof(resourceProjectName.ApplicationStrings), ErrorMessageResourceName = "ValidationText")] //this does not work
public string Property { get; set; }
Html示例:
这是在Html.BeginForm中。如果缺少某些内容或无效,则会在POST请求后显示验证消息。
<div>
<div class="form-group row">
<div>
@Html.LabelFor(x => x.Property)
</div>
<div class="col-sm-6">
@Html.TextBoxFor(x => x.Property, new { @class = "form-control" })
</div>
@if (ViewData.ModelState.Where(i => i.Key.Equals("Property")).Any(x => x.Value.Errors.Any()))
{
<div class="col-sm-6">
@Html.ValidationMessageFor(x => x.Property, "", new { @class = "alert-validation alert-danger" })
</div>
}
</div>
</div>
的Web.config:
<globalization culture="auto" uiCulture="auto" enableClientBasedCulture="true"/>
本地化适用于网站上的所有内容,但验证消息除外。
它始终显示与浏览器语言设置匹配的资源字符串,尽管用户导航到例如:site.de/en-EN/test。
web.config有问题吗?我试图将enableClientBasedCulture设置为false,但问题仍然存在。
亲切的问候, 马丁
答案 0 :(得分:3)
我在这里找到了解决问题的方法:http://afana.me/post/aspnet-mvc-internationalization.aspx
我所做的是删除我的“国际化”属性并创建一个“BaseController”类,它基本上与每个请求上的“国际化”属性做同样的事情。
Basecontroller:
public class BaseController : Controller
{
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
//Localization in Base controller:
string language = (string)RouteData.Values["language"] ?? "de";
string culture = (string)RouteData.Values["culture"] ?? "DE";
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));
return base.BeginExecuteCore(callback, state);
}
}
本地化现在可用于标签和验证消息。