ASP.NET MVC2 中使用多语言

来源:互联网 发布:python requests的功能 编辑:程序博客网 时间:2024/05/16 10:19

1、创建一个 ASP.NET MVC 2空项目

然后添加Home控制器,HomeController类内容如下:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Globalization;namespace MvcAJAX.Controllers{    public class HomeController : Controller    {        //        // GET: /Home/        public ActionResult Index()        {            return View();        }        public ActionResult ChangeCulture(string lang, string returnUrl)        {            Session["Culture"] = new CultureInfo(lang);            return Redirect(returnUrl);        }    }}

 

2、为Home创建Index视图,内容如下:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>Index</title></head><body>    <div>        <%=Html.ActionLink("English","ChangeCulture",new{lang="en-us",returnUrl=this.Request.RawUrl},null) %>        <br />        <%=Html.ActionLink("简体中文", "ChangeCulture", new { lang = "zh-cn", returnUrl = this.Request.RawUrl }, null)%>        <br />        [<%=ViewResources.Index.Name%>]    </div></body></html>


 

3、添加资源文件

在根目录中添加Resources文件夹,在其中添加 Default 子文件夹,在Default中再添加Home子文件夹。

在Home中添加资源文件:Index.resx和Index.en-us.resx

把Index.resx命名空间定义为:ViewResources

修改两个文件的访问属性为:public

并为两个资源中都添加名称为Name的变量,分别为中文、英文字符串。

 

4、修改Global.asax文件内容,添加如下代码:


 

protected void Application_AcquireRequestState(object sender, EventArgs e)        {            if (HttpContext.Current.Session != null)            {                CultureInfo cultureInfo = (CultureInfo)this.Session["Culture"];                // 判断Session中是否有值,没有就设置默认值                if (cultureInfo == null)                {                    string langName = "zh-cn";                    if (HttpContext.Current.Request.UserLanguages != null && HttpContext.Current.Request.UserLanguages.Length != 0)                    {                        langName = HttpContext.Current.Request.UserLanguages[0];                    }                    cultureInfo = new CultureInfo(langName);                    this.Session["Culture"] = cultureInfo;                }                Thread.CurrentThread.CurrentCulture = cultureInfo;                Thread.CurrentThread.CurrentUICulture = cultureInfo;                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);                Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);            }        }


       

 

5、访问 /Home/Index 测试效果

 

示例下载:http://download.csdn.net/detail/xz2001/4143788