提示: 不要在MasterPage的Page_Init事件中设置区域信息

一般地, 我们的是在Page的InitializeCulture事件中更改当前线程的区域信息的, 常规的示例如下: 

   protected override void InitializeCulture()
    {
        base.InitializeCulture();

        string s = Request.QueryString["currentculture"];
        if (!String.IsNullOrEmpty(s))
        {
            CultureInfo culture = CultureInfo.CreateSpecificCulture(s);
            Thread.CurrentThread.CurrentUICulture = culture;
            Thread.CurrentThread.CurrentCulture = culture;
        }
    }

Problem:

但是, 当我们想改变整站的区域信息以达到整站本地化时, 我一开始走了一条弯路, 使用了MasterPage的Page_Init事件, 具体如下:

    protected void Page_Init(object sender, EventArgs e)
{
string s = Request.QueryString["currentculture"];
if (!String.IsNullOrEmpty(s))
{
CultureInfo culture = CultureInfo.CreateSpecificCulture(s);
Thread.CurrentThread.CurrentUICulture = culture;
Thread.CurrentThread.CurrentCulture = culture;
}
}
, Page中的HTML代码如下:
        <asp:Label ID="Label1" runat="server" Text="<%$Resources:labels, lblText %>"></asp:Label>
<hr />
<label><%=Resources.labels.lblText %></label>
<hr />
<a href="?currentculture=zh-cn">中文(中国)</a><br />
<a href="?currentculture=en">English(USA)</a>
<asp:Button ID="Button1" runat="server" Text="<%$Resources:labels, lblText %>" />

 

运行效果并不像我们想像中的一样:

image

只有<label><%=Resources.labels.lblText %></label> 本地化了, 服务器端控件如Asp:Label并没有按照我们选择的区域信息正确显示.

 

Why?

我们查看一下MasterPage, 再看看它继承自UserControl, 显示, 它与服务器端控件的生命周期时间是一致的, 并不早于服务器端控件(前面说的是Asp:Label), 所有在MasterPage的Init事件设置区域信息, 对于服务器端控件来说, 已经太晚了.

想更加了解Page的生命周期, 可查看下面这张图片(摘自网络)

ASP_NET-2_0-life-cycle

 

How to do it right?

若要想实现整站设置相同的区域信息, 目前我认为最佳的方式是使用BasePage, 让每个页面都继承着BasePage, 然后按照上面的方法重写InitializeCulture来实现.

 

参考文章:

1. ASP.NET 2.0 本地化技术之研究(二)

posted @ 2007-07-04 00:25  MK2  阅读(1346)  评论(0编辑  收藏  举报