Why doesn't the language change on postback?

2019-05-31 09:10发布

问题:

My dropdownlist has a list of languages with values in the form of en-NZ, en-US etc but the page doesn't change the language on postback is my language codes wrong. Could someone have a look at my code and tell me what I'm doing wrong to change the language for my page

And my lbllanguage.Text changes on the second postback aswell so it's suppose to change on the ChangeLanguage_Click event first time it is clicked

Main Page:

protected void Page_PreRender(object sender, EventArgs e)
{
    string Culture = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture;
    if (ddlChangeLanguage.Items.FindByValue(Culture) != null)
    {
        ddlChangeLanguage.SelectedValue = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture; 
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        List<CultureInfo> languages = CultureInfo.GetCultures(CultureTypes.SpecificCultures).OrderBy(x => x.Name).ToList();

        SortedDictionary<string, string> sortedLanguages = new SortedDictionary<string, string>();

        foreach (CultureInfo language in languages)
        {
            RegionInfo regionInfo = new RegionInfo(language.Name);
            if (!sortedLanguages.ContainsKey(regionInfo.EnglishName))
            {
                sortedLanguages.Add(regionInfo.EnglishName, language.Name);
            }
        }

        foreach (KeyValuePair<string, string> language in sortedLanguages)
        {
            ddlChangeLanguage.Items.Add(new ListItem { Value = language.Value, Text = language.Key });
        }
        ddlChangeLanguage.SelectedValue = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture;
    }
    lbllanguage.Text = this.UICulture;

}

protected void ChangeLanguage_Click(object sender, EventArgs e)
{
    (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture = ddlChangeLanguage.SelectedValue;
}

and my BasePage which my main page inherits

public class BasePage : System.Web.UI.Page
{
    public BasePage()
    {
    }

    protected override void InitializeCulture()
    {            
        this.Culture = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture;
        this.UICulture = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture;
    }
}

回答1:

You have to store your strings in a resource file or satellite assemblies for translations to happen:

ASP.NET Web Page Resources Overview

<asp:Button ID="Button1" runat="server" 
    Text="<%$ Resources:WebResources, Button1Caption %>" />


回答2:

Configure the current thread too:

var culture = (HttpContext.Current.Profile as ProfileCommon).Preferences.Culture;
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;


回答3:

Try changing the logic in Page_PreRender to a handler for DropDownList.SelectedIndexChanged.