Reputation: 1381
I have created an application where I require is to change the culture in the drop down selection.
This is my action method code.
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);
}
This seems to be working but I have dynamic values list whose values are not added in the resource file and I am getting blank properties values in the view. I need to print all the values in the view. How can I achieve this?
Thanks in Advance
Upvotes: 0
Views: 915
Reputation: 1359
If it isn´t in the resource file it will be blank. You could, however have a default resource file and specialized ones. If it has value you fill with the specialized if not the default.
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");
}
Upvotes: 1