MVC
▌目的
l 實作一Website可由瀏覽器預設語系來顯示對應語系之文字。
l 加入可由使用者選擇語系並存入cookie作為未來預設之語系。
▌環境
|
▌實作2
這邊要開始建立以使用者選擇喜好語系,並存入Cookie的方式,來偵測(加強)顯示的語系。
▋CultureHelper
l 預設網站支援的語系
PS. 也可改將這些資料維護在資料庫。
PS. 也可改將這些資料維護在資料庫。
public enum CultureEnum
{
/// <summary>
/// 中文(繁體)
/// </summary>
[Description("zh-TW")]
zhTW =0,
/// <summary>
/// 中文(简体)
/// </summary>
[Description("zh-CN")]
zhCN,
/// <summary>
/// 英文
/// </summary>
[Description("en-US")]
enUS
}
|
l CultureHelper
/// <summary>
/// CultureHelper for 多國語言開發
/// </summary>
public class CultureHelper
{
/// <summary>
/// Culture object declaration
/// </summary>
public class Culture
{
public int Key {get;set;}
public String Value {get;set;}
}
/// <summary>
/// 取得已對應的語言系(如果沒有對應的則以預設為主)
/// </summary>
/// <param
name="culture">選擇的語系</param>
/// <returns>對應的語系</returns>
public static String GetImplementedCulture(String culture)
{
bool isImplemented = false;
if(!String.IsNullOrEmpty(culture))
{
isImplemented =
(GetAllImplementedCultures().Where(x => x.Value.Equals(culture)).Count()
> 0) ? true : false;
}
if(!isImplemented)
{
return getDefaultCulture();
}
else
{
return culture;
}
}
/// <summary>
/// 取得所有有建立的語系
/// </summary>
/// <remarks>通常是給下拉式選單使用</remarks>
/// <returns>語系集合</returns>
public static IEnumerable<Culture> GetAllImplementedCultures()
{
List<Culture> cultureList = new List<Culture>();
foreach(CultureEnum cl in Enum.GetValues(typeof(CultureEnum)))
{
cultureList.Add(new Culture {
Key = cl.ToIntValue(),
Value = cl.GetDescription() });
}
return cultureList.AsEnumerable<Culture>();
}
private static String getDefaultCulture()
{
return CultureEnum.enUS.GetDescription(); //預設為en-US 英文
}
}
|
l MVC : 選擇預設語系(View Model)
public class CultureVm
{
[Display(Name = "CultureName", ResourceType = typeof(MultiLangResx.Resources.Resource))]
public String Name { get; set; }
}
|
l MVC : 選擇預設語系(View)
@using
MyMultiLangWebSite.Extensions;
@model MyMultiLangWebSite.Models.CultureVm
@using
(Html.BeginForm())
{
@Html.AntiForgeryToken()
<br />
<div>
<b>Current Language:@ViewBag.CookieCulture</b>
</div>
<hr />
<table class="table">
<tr>
<td>
@Html.DisplayNameFor(model =>
model.Name)
</td>
<td>
@Html.DropDownListFor(model =>
model.Name, (IEnumerable<SelectListItem>)ViewData["LangSelectList"])
</td>
<td>
<input type="submit"
value="@Html.DisplayName( "Submit".ToAutoMultiLang())">
</td>
</tr>
</table>
}
|
l MVC : 選擇預設語系(Controller)
public class MultiLangController : Controller
{
public ActionResult Index()
{
#region Show the culture saved in Cookie
HttpCookie cultureCookie = Request.Cookies["_culture"];
if (cultureCookie != null)
{
ViewBag.CookieCulture =
cultureCookie.Value as String;
}
else
{
ViewBag.CookieCulture = "(None)";
}
#endregion
#region Get DropDownList items
//ViewData
ViewData["LangSelectList"] = CultureHelper.GetAllImplementedCultures()
.ToSelectList(x => x.Value,
x => x.Value, isOrder: true)
as IList<SelectListItem>;
return View();
}
// POST: MultiLang/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(CultureVm vm)
{
try
{
#region 更改語系
var culture = CultureHelper.GetImplementedCulture(vm.Name);
HttpCookie cultureCookie = Request.Cookies["_culture"];
if (cultureCookie != null)
{
cultureCookie.Value = culture;
}
else
{
cultureCookie = new HttpCookie("_culture");
cultureCookie.HttpOnly = true;
cultureCookie.Value = culture;
cultureCookie.Expires = DateTime.Now.AddMonths(2);
}
Response.Cookies.Add(cultureCookie);
//設定Current Culture
var ci = new CultureInfo(culture);
System.Threading.Thread.CurrentThread.CurrentUICulture
= ci;
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
#endregion
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
|
l 調整 Global.asax
最後,在每次收到Request的時候,由HttpResponse的語系喜好為主,改為:
當已經設定Cookie時,以Cookie之設定為主。
protected void
Application_BeginRequest(object sender, EventArgs e)
{
HttpCookie cultureCookie = Request.Cookies["_culture"];
CultureInfo ci = null;
try
{
if (cultureCookie != null) //已設定Culture Cookie,則以Cookie為主
{
ci = new CultureInfo(cultureCookie.Value);
}
else //未設定Culture Cookie,以HttpRequest的資訊為主
{
//取得用戶端語言喜好設定(已排序的字串陣列)
//略 … 請參考實作1
}
}
catch (Exception)
{
throw;
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture
= ci;
System.Threading.Thread.CurrentThread.CurrentCulture
= ci;
}
}
|
▌Reference
沒有留言:
張貼留言