HttpCookie加匿名類實現多語言

忽然想作一個多語言網站,確不知道怎麼實現好,忽然想到了HttpCookie,而後頁面後臺用匿名類實現語言的儲存。cookie

            string lan = Request["str_lan"];
            ViewBag.lan = lan;

            HttpCookie hc = new HttpCookie("language");
            hc.Value = lan;
            hc.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(hc);        

HttpCookie用來當前記錄語言種類。post

 

前臺頁面取值:網站

@{
    ViewBag.Title = "Home Page";
    var language = new Dictionary<string, object>();
    language.Add("zh_cn", new { name = "鄧永高" });
    language.Add("en", new { name = "dyg" });

    string get_lan = string.Empty;
    HttpCookie cookie_language = Request.Cookies["language"];
    if (cookie_language != null)
    {
        get_lan = cookie_language.Value;
    }

}


@using MVCMutiLan.Controllers;

<h2>@Html.getPageLanVal(language, get_lan, "name").ToString()</h2>
<form action="/Home/Index" method="post">

    <select name="str_lan">
        <option value="zh_cn">簡體中文</option>
        <option value="en">英文</option>
    </select>  <input type="submit" value="設置語言" />

</form>

@ViewBag.lan

 

控件取值的擴展方法:this

 public static class HtmlHelpers
    {
        public static object getPageLanVal(this HtmlHelper helper, Dictionary<string, object> dic, string strlan, string Lanvalue)
        {
            return dic[strlan].GetType().GetProperties().Where(x => x.Name == Lanvalue).FirstOrDefault().GetValue(dic[strlan]);
        }
    }
相關文章
相關標籤/搜索