1.创建项目添加App_GlobalResources文件夹
2.添加资源文件Global.resx
3.添加资源文件内容
4..创建全局过滤器
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); }
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new LanageFilter()); } }
public class LanageFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var lang = filterContext.HttpContext.Session["lanage"]; if (lang==null) { lang = "zh"; } Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(lang.ToString()); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture; filterContext.HttpContext.Session["lanage"] = lang; } }
5.创建更新session的方法
[HttpGet] public JsonResult ChangeLanage(string lang) { Session["lanage"] = lang; return Json("true", JsonRequestBehavior.AllowGet); }
6.写页面点击事件
$("#zn").click(function () { $.ajax({ url: '@Url.Action("ChangeLanage", "Home")', type: "get", dataType: "json", data: { "lang": "zn" }, success: function (data) { if (data) { window.location.reload(); } } }) })
7.显示信息
<h2>@Resources.Global.Index</h2>
8。语言资源文件命名要规范否则会报错应以Global.zh-cn.resx 格式