2017-08-24 157 views
0

我已經創建了一個應用程序,我需要的是更改下拉選擇中的文化。在下拉選擇中更改文化

這是我的動作方法代碼。

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

我不完全理解你想要在for循環中做什麼。你能詳細說明一下嗎? – PedroSouki

+0

我不確定我的代碼是否正確。使用for循環我想將資源值傳遞給列表中的視圖?這是對的嗎? –

+0

您可以訪問視圖中的資源。你不需要這個循環。像這樣訪問'@Resources.Resource.AddressCountry' – PedroSouki

回答

1

如果isn't在資源文件時,它將會是空白。不過,你可以有一個默認的資源文件和專門的文件。如果它具有價值,那麼填寫專業的,如果不是默認的話。

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"); 
} 
相關問題