自动回退正在将Asp.net页面上的语言重置为默认值
本文关键字:语言 默认值 回退 net Asp | 更新日期: 2023-09-27 18:07:52
我希望用户从下拉列表中选择他们选择的语言。这工作得很好,我正在使用global_resource。然而,当我从另一个下拉菜单(Autopostback =true)中选择一个选项时,语言会从法语变回英语。我是否需要在会话中存储语言选择以防止这种情况,如果是这样,我可以有一个例子或指向教程。谢谢你。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (ddlLanguages.Items.FindByValue(CultureInfo.CurrentCulture.Name) != null)
{
ddlLanguages.Items.FindByValue(CultureInfo.CurrentCulture.Name).Selected = true;
}
}
}
protected override void InitializeCulture()
{
string language = "en-GB";
//Detect User's Language.
if (Request.UserLanguages != null)
{
//Set the Language.
language = Request.UserLanguages[0];
}
//Check if PostBack is caused by Language DropDownList.
if (Request.Form["__EVENTTARGET"] != null && Request.Form["__EVENTTARGET"].Contains("ddlLanguages"))
{
//Set the Language.
language = Request.Form[Request.Form["__EVENTTARGET"]];
}
//Set the Culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}
protected void ddlTest_SelectedIndexChanged(object sender, EventArgs e)
{
lblShow.Visible = true;
}
}
最好将用户选择的语言存储在会话中,并在以后的页面请求中使用该值
protected override void InitializeCulture()
{
string language = "en-GB";
//Detect User's Language.
// if (Request.UserLanguages != null)
// {
//Set the Language.
// language = Request.UserLanguages[0];
// }
//Check if PostBack is caused by Language DropDownList.
if (Request.Form["__EVENTTARGET"] != null && Request.Form["__EVENTTARGET"].Contains("ddlLanguages"))
{
//Set the Language.
language = Request.Form[Request.Form["__EVENTTARGET"]];
Session["language"]=language.ToString();
}
else
{
if(Session["language"] !=null){
language=Session["language"].ToString();
}
}
//Set the Culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}
您需要将语言存储在会话或cookie中。现在发生的事情是,当您初始化来自其他控件的回发时,语言将在行中设置language = Request.UserLanguages[0];
应该是英文。会话/cookie解决方案还使您能够为来自同一用户的其他非回发请求持久化语言选择。