ASP.NET MVC 4 View ( Razor ) + Customize HTML Helper + Session + Resource + Locale 方法
Global.asax.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace MvcApplication { public class MvcApplication : System.Web.HttpApplication { … … void Application_AcquireRequestState(object sender, EventArgs e) { HttpContext context = HttpContext.Current; if (context.Request.QueryString["Cult"] != null) { if (context.Request.QueryString["Cult"].ToString().Trim().ToUpper().Equals("CN")) { if (context != null && context.Session != null) { context.Session["Cult"] = "CN"; } } else if (context.Request.QueryString["Cult"].ToString().Trim().ToUpper().Equals("EN")) { if (context != null && context.Session != null) { context.Session["Cult"] = "EN"; } } } } } } |
\App_GlobalResources\ResourceCN.resx |
<?xml version="1.0" encoding="utf-8"?> <root> … … <data name="MenuAsia" xml:space="preserve"> <value>亞洲</value> </data> <data name="MenuHome" xml:space="preserve"> <value>主頁</value> </data> <data name="MenuWorld" xml:space="preserve"> <value>環球</value> </data> </root> |
\App_GlobalResources\ResourceEN.resx |
<?xml version="1.0" encoding="utf-8"?> <root> … … <data name="MenuAsia" xml:space="preserve"> <value>Asia</value> </data> <data name="MenuHome" xml:space="preserve"> <value>Home</value> </data> <data name="MenuWorld" xml:space="preserve"> <value>World</value> </data> </root> |
\Library\ViewHelper.cs |
using System; using System.Web.Mvc; using System.Resources; using System.Reflection; namespace MvcApplication.Library { public static class ViewHelper { … … public static MvcHtmlString Culture(this string value) { ResourceManager resourcemanager; if (System.Web.HttpContext.Current.Session["Cult"] != null) { if(System.Web.HttpContext.Current.Session["Cult"].Equals("CN")){ resourcemanager = new ResourceManager("Resources.ResourceCN", Assembly.Load("app_globalresources")); return MvcHtmlString.Create(resourcemanager.GetString(value)); } else if (System.Web.HttpContext.Current.Session["Cult"].Equals("EN")) { resourcemanager = new ResourceManager("Resources.ResourceEN", Assembly.Load("app_globalresources")); return MvcHtmlString.Create(resourcemanager.GetString(value)); } } resourcemanager = new ResourceManager("Resources.ResourceCN", Assembly.Load("app_globalresources")); return MvcHtmlString.Create(rm.GetString(value)); } } } |
\Views\Home\Index.cshtml |
<li class="menu">@("MenuHome".Culture())</li> <li class="menu">@("MenuWorld".Culture())</li> <li class="menu">@("MenuAsia".Culture())</li> |