我的MVC项目存在问题,我需要用户能够在运行时更改网站的本地化,我的代码是我到目前为止所尝试的,当然文化确实改变了,但是我发现我的网站没有任何变化。
奇怪的是,在Web.Config中设置文化可以正常工作!
我的代码如下,有任何想法吗?
[AllowAnonymous]
[HttpPost]
public ActionResult SelectLanguage(LoginViewModel model)
{
switch (model.SelectedLanguage)
{
case "French":
CultureInfo.CurrentCulture=new CultureInfo("fr-fr");
CultureInfo.CurrentUICulture = new CultureInfo("fr-fr");
break;
}
return RedirectToAction("Index");
}
答案 0 :(得分:2)
这样做的好方法是制作一个在浏览器中设置cookie的方法:
public void ChangeCulture(string lang)
{
Response.Cookies.Remove("Language");
HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["Language"];
if (languageCookie == null) languageCookie = new HttpCookie("Language");
languageCookie.Value = lang;
languageCookie.Expires = DateTime.Now.AddDays(10);
Response.SetCookie(languageCookie);
Response.Redirect(Request.UrlReferrer.ToString());
}
在此之后(这个棘手的方法)你需要让每个控制器都从一个BaseController继承。这很棘手,因为你需要覆盖Initialize。
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["Language"];
if (languageCookie != null)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(languageCookie.Value);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(languageCookie.Value);
}
else
{
//other code here
}
base.Initialize(requestContext);
}
并在方法调用ChangeCulture()
中使用lang
[AllowAnonymous]
[HttpPost]
public ActionResult SelectLanguage(LoginViewModel model)
{
switch (model.SelectedLanguage)
{
case "French":
ChangeCulture("fr-Fr");
break;
}
return RedirectToAction("Index");
}
答案 1 :(得分:0)
这个问题Change culture based on a link MVC4帮了很多忙!
基本上我需要覆盖我的资源字符串的文化,而不是实际应用程序的文化!
我的代码已更改为此内容;
[AllowAnonymous]
[HttpPost]
public ActionResult SelectLanguage(LoginViewModel model)
{
switch (model.SelectedLanguage)
{
case "French":
LanguageStrings.Culture = new CultureInfo("fr-fr");
break;
}
return RedirectToAction("Index");
}
和魅力一样! = d