Asp.net MVC multi-language application
The following uses the logon page of The Mvc3 template project as an example to describe the process: Prepare the resource file, that is, the Language Pack. Add the Resource folder for the web site project, and then add two resx FILE command line tools under the Resource folder resgen.exe generate the two resx files with the same name as the resources file, such as zh-CN.resources, en-US.resources, put the two resources files into the Resource Directory and write a static getLang file.
namespace System.Web.Mvc{ using System.Collections; using System.Resources; using System.Linq; public static class LocalizationHelper { public static string Lang(this HtmlHelper html, string key) { return GetLang(key); } public static string GetLang(string key) { var filePath = HttpContext.Current.Server.MapPath("~/Resource"); string language = HttpContext.Current.Session["CurrentLanguage"] == null ? "zh-CN" : HttpContext.Current.Session["CurrentLanguage"].ToString(); string resxPath = string.Format(@"{0}\{1}.resources", filePath, language); ResourceReader reader = new ResourceReader(resxPath); var entry = reader.Cast<DictionaryEntry>().FirstOrDefault<DictionaryEntry>(x => x.Key.ToString() == key); reader.Close(); return entry.Value == null ? "" : (string)entry.Value; } public static string GetLanguage(this HtmlHelper html) { return HttpContext.Current.Session["CurrentLanguage"].ToString(); } }}
Step 2: For the dynamic switching language, add the Application_AcquireRequestState event to the Global. asax file, for example:
protected void Application_AcquireRequestState(object sender, EventArgs e) { if (HttpContext.Current.Session != null) { System.Globalization.CultureInfo ci = (System.Globalization.CultureInfo)this.Session["CurrentLanguage"]; if (ci == null) { ci = new System.Globalization.CultureInfo(Request.UserLanguages[0].ToString()); this.Session["CurrentLanguage"] = ci; } System.Threading.Thread.CurrentThread.CurrentUICulture = ci; System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(ci.Name); } }
Step 3: add the ChangeLanguage method to HomeController, which is very simple and just a piece of code, such:
Public JsonResult ChangeLanguage () {string aa = Request ["language"]; Session ["CurrentLanguage"] = new System. globalization. cultureInfo (Request ["language"]); return Json ("operation successful! ", JsonRequestBehavior. AllowGet );}