如何创建一个类来初始化文化以进行本地化

时间:2014-04-06 14:21:12

标签: c# asp.net localization

我正在尝试本地化我的asp.net页面。到目前为止,我只是本地化我的母版页。

Global.asax中

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpCookie cookie = Request.Cookies["CultureInfo"];

    if (cookie != null && cookie.Value != null)
    {
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(cookie.Value);
        Thread.CurrentThread.CurrentCulture = new CultureInfo(cookie.Value);
    }
    else
    {
        Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-CA");
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
    }
}

MasterPage.master.cs

protected void Page_Load(object sender, EventArgs e)
{
    //only does it on non-postback because otherwise 
    //the selected value will not reach event handler correctly
    if (!Page.IsPostBack)
    {
        ddlLanguage.SelectedValue = Thread.CurrentThread.CurrentCulture.Name;
    }
}

protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
    //Sets the cookie that is to be used by Global.asax
    HttpCookie cookie = new HttpCookie("CultureInfo");
    cookie.Value = ddlLanguage.SelectedValue;
    Response.Cookies.Add(cookie);

    //Set the culture and reload for immediate effect.
    //Future effects are handled by Global.asax
    Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlLanguage.SelectedValue);
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlLanguage.SelectedValue);
    Server.Transfer(Request.Path);
}

MasterPage.master

<asp:DropDownList ID="ddlLanguage" runat="server"
        OnSelectedIndexChanged="ddlLanguage_SelectedIndexChanged"
        AutoPostBack="true">
        <asp:ListItem Text="<%$ Resources:Resource, users_English %>" Value="en-CA" />
        <asp:ListItem Text="<%$ Resources:Resource, users_French %>" Value="fr-CA" />
</asp:DropDownList>

如何为所有其他网页创建一个公共类,以便从公共类继承。

1 个答案:

答案 0 :(得分:1)

您可以创建一个继承自System.Web.Ui.Page的类(即公共类CommonPage:System.Web.Ui.Page)添加/覆盖您想要的方法,并且您的所有页面都可以从这个新创建的方法继承。