[转thyking xiao's blog]asp.net 2.0实现多语言(一)

1.新建一个asp.net web应用程序


2.创建的项目如下图所示


3.右击web项目名称,添加一个全局资源文件夹"app_GlobalResources" ,这个是asp.net 2.0特有的


4.右击"app_GlobalResources"文件夹,添加两个资源文件: language.resx(简体资源文件)  和language.en-us.resx (英文的资源文件)




5.打开两个资源文件,添加相应的资源信息,如下图所示




6.打开default.aspx文件,输入如下代码:
<body>
    <form id="form1" runat="server">
    <center>
        <div style="margin: 20px; padding: 10px; height: 200px; width: 200px; border: solid 1px #C0C0C0;
            text-align: center;">
            <br />
            <a href="?curlanguage=zh-cn">中文</a> &nbsp;
             <a href="?curlanguage=en-us">英文</a>
            <br />
            <br />
            国家:&nbsp;<asp:Literal ID="ltlcountry" runat="server"></asp:Literal>
            <br />
            城市:&nbsp;<asp:Literal ID="ltlcity" runat="server"></asp:Literal>
           
             <br />
            <br />
            国家2:&nbsp;<asp:Literal ID="ltlcountry2" runat="server"></asp:Literal>
            <br />
            城市2:&nbsp;<asp:Literal ID="ltlcity2" runat="server"></asp:Literal>
        </div>
    </center>
    </form>
</body>


预览如下图所示:


7.打开Default.aspx.cs文件,输入如下代码:

  

//这段代码很重要 
protected override void InitializeCulture()
        {
            string culture = Request.QueryString["curlanguage"];
            if (!String.IsNullOrEmpty(culture))
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(culture);
                System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(culture);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ltlcountry.Text = Resources.language.country.ToString();
                ltlcity.Text = Resources.language.city.ToString();

                ltlcountry2.Text =(string)GetGlobalResourceObject("language", "country");
                ltlcity2.Text=(string)GetGlobalResourceObject("language", "city");

            }
        }

8. build下整个项目,按F5浏览: 点击下图中的  "中文" 和 "英文" 链接就可以查看我们所要的效果了



posted @ 2008-10-08 15:32  meetweb  阅读(966)  评论(1编辑  收藏  举报