在btn点击时更改资源文件引用

时间:2014-04-15 18:17:11

标签: c# asp.net multilingual resx

我正在为用户实现一种切换显示语言的方式(en || es)。我有以下内容:

<asp:LinkButton ID="Lnk_cultChange" runat="server" Text="<%$Resources:mySource, cultbtn%>" OnClick="cultChange_Click" />

代码背后:

protected void cultChange_Click(object sender, EventArgs e)
{
    if (CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "en")
    {
        System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-ES");
        System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
        base.InitializeCulture();
    }
    else
    {
        System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
        System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
        base.InitializeCulture();
    }
}

有一个回发,但似乎没有任何事情发生。英语资源文件仍在显示,不进行翻译。我的实施是否正确?

3 个答案:

答案 0 :(得分:0)

在页面PreInit事件上切换文化,如果您只想在单击特定按钮时切换文化,则使用以下代码。

protected override void OnPreInit(EventArgs e)
{
    if (Page.IsPostBack)
    {
        if (Request.Form["__EVENTTARGET"] == "Lnk_cultChange")
        {
            if (CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "en")
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-ES");
                System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
                base.InitializeCulture();
            }
            else
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
                System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                base.InitializeCulture();
            }
        }

    }

    base.OnPreInit(e);
}

Request.Form [“__ EVENTTARGET”]将是您的LinkBut​​ton的客户端ID,如果这不起作用,请告诉我

答案 1 :(得分:0)

将更改lang按钮放在站点主站中。 添加点击事件处理程序,如下所示

protected void btnEng_Click(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en");
    Session.Add("Lang", "en");
    Response.Redirect(Request.Url.PathAndQuery);
}

在您的网页中&#39;代码后面添加以下方法:

protected override void InitializeCulture()
    {
        if (Session["Lang"] != null)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Session["Lang"].ToString().Split('-')[0]);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(Session["Lang"].ToString().Split('-')[0]);
        }
        else
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
        }
        base.InitializeCulture();
    }

希望有所帮助

答案 2 :(得分:0)

就像@Umriyaev建议你必须覆盖InitializeCulture()并使用它来在另一个重定向之后拉动文化。见https://stackoverflow.com/a/10672476/2596756