视图页:
<div>
@Html.ActionLink("简体中文", "ChangeCulture", "Home", new { lang = "zh-CN", returnUrl = this.Request.RawUrl }, new { target = "_parent", @class = "btn btn-primary btns" })
@Html.ActionLink("English", "ChangeCulture", "Home", new { lang = "en-US", returnUrl = this.Request.RawUrl }, new { target = "_parent", @class = "btn btn-primary btns" })
@Html.ActionLink("繁體中文", "ChangeCulture", "Home", new { lang = "zh-TW", returnUrl = this.Request.RawUrl }, new { target = "_parent", @class = "btn btn-primary btns" })
@Html.ActionLink("한글", "ChangeCulture", "Home", new { lang = "ko-KR", returnUrl = this.Request.RawUrl }, new { target = "_parent", @class = "btn btn-primary btns" })
<h1>@Html.GetLangByKey("这是一个标题")</h1>
<a href="/Home/Index">@Html.GetLangByKey("第二个页面")</a>
</div>
控制器:
public ActionResult ChangeCulture(string lang,string returnUrl)
{
Session["Culture"] = new CultureInfo(lang);
return Redirect(returnUrl);
}
添加资源文件,并将不同语言的翻译输入。
LanguageHelper类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Web.Mvc;
using WebApplication1.Models;
using System.Reflection;
namespace WebApplication1.Models
{
public static class LanguageHelper
{
/// <summary>
/// 中英文转换
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetLangByKey(this HtmlHelper htmlHelper,string key)
{
Type resourceType = null;
string typeName = Thread.CurrentThread.CurrentUICulture.Name;
switch (typeName)
{
case "zh-CN":
resourceType = typeof(WebApplication1.Resources.zh_CN); //zh_CN为资源文件名
break;
case "en-US":
resourceType = typeof(WebApplication1.Resources.en_US);
break;
case "zh-TW":
resourceType = typeof(WebApplication1.Resources.zh_TW);
break;
case "ko-KR":
resourceType = typeof(WebApplication1.Resources.ko_KR);
break;
default:
resourceType = typeof(WebApplication1.Resources.zh_CN);
break;
}
PropertyInfo propertyInfo = resourceType.GetProperty(key);
if (propertyInfo != null)
{
return propertyInfo.GetValue(null, null).ToString();
}
else
{
return key;
}
}
}
}
Global.asax中添加:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
CultureInfo cultureInfo = (CultureInfo)this.Session["Culture"];
if (cultureInfo == null)
{
string langName = "zh-CN";
cultureInfo = new CultureInfo(langName);
this.Session["Culture"] = cultureInfo;
}
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
}
}