我创建了一个应用程序,我需要在下拉选项中更改文化。
这是我的行动方法代码。
public ActionResult SetCulture(string lang)
{
if (lang == "en")
return RedirectToAction("Index");
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(lang.Trim()); //.TextInfo.IsRightToLeft;
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang.Trim());
List<Agent> lstMainAgent = new List<Agent>();
List<Agent> lstAgent = db.Agents.ToList();
for (int i = 0; i < lstAgent.Count(); i++)
{
lstAgent[i].AddressCity = Resources.Resource.AddressCity;
lstAgent[i].AddressCountry = Resources.Resource.AddressCountry;
lstAgent[i].AddressPostcode =Resources.Resource.AddressPostcode;
lstAgent[i].AddressStreet = Resources.Resource.AddressStreet;
lstAgent[i].Name = Resources.Resource.Name;
lstAgent[i].PhoneNumber = Resources.Resource.PhoneNumber;
lstMainAgent.Add(lstAgent[i]);
}
return View("Index", lstMainAgent);
}
这似乎有效,但我有动态值列表,其值未添加到资源文件中,我在视图中获取空白属性值。我需要在视图中打印所有值。我怎样才能做到这一点?
提前致谢
答案 0 :(得分:1)
如果它不在资源文件中,则它将为空白。但是,您可以使用默认资源文件和专用文件。如果它具有值,则使用专用而不是默认值填充。
public ActionResult SetCulture(string culture)
{
try
{
// set a default value
if (string.IsNullOrEmpty(culture))
{
culture = "en-US";
}
// set the culture with the chosen name
var cultureSet = CultureInfo.GetCultureInfo(culture);
Thread.CurrentThread.CurrentCulture =cultureSet;
Thread.CurrentThread.CurrentUICulture = cultureSet;
// set a cookie for future reference
HttpCookie cookie = new HttpCookie("culture")
{
Expires = DateTime.Now.AddMonths(3),
Value = culture
};
HttpContext.Response.Cookies.Add(cookie);
List<Agent> lstAgent = db.Agents.ToList();
foreach (Agent item in lstAgent)
{
item.AddressCity = Resources.Resource.AddressCity;
item.AddressCountry = Resources.Resource.AddressCountry;
item.AddressPostcode = Resources.Resource.AddressPostcode;
item.AddressStreet = Resources.Resource.AddressStreet;
item.Name = Resources.Resource.Name;
item.PhoneNumber = Resources.Resource.PhoneNumber;
}
return View("Index", lstAgent);
}
catch (Exception ex)
{
// if something happens set the culture automatically
Thread.CurrentThread.CurrentCulture = new CultureInfo("auto");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("auto");
}
return View("Index");
}