2015-12-14 48 views
-2

我有一個字典在我的mvc控制器和存儲值,所以我想顯示這些值使用視圖。如何使用mvc視圖顯示字典值

我的代碼

public List<Dictionary<string, string>> getalllocation() 
    { 
     var locs = new List<Dictionary<string, string>>(); 
     try 
     { 
      DataTable dt1 = new DataTable(); 
      string connString = cnst.cnstrin(); 
      string query = "SELECT * FROM `Mytable`.`location`"; 
      MySqlDataAdapter ma = new MySqlDataAdapter(query, connString); 
      DataSet DS = new DataSet(); 
      ma.Fill(dt1); 

      foreach (DataRow drow in dt1.Rows) 
      { 
       Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
       dictionary.Add("id", drow["LocationId"].ToString()); 
       dictionary.Add("name", drow["LocationName"].ToString()); 
       locs.Add(dictionary); 
      } 
      } 
     catch (MySqlException e) 
     { 
      throw new Exception(e.Message); 
     } 
     return locs; 
     } 

我我的觀點

@{ 
    List<Dictionary<string,string>>locations=((HomeController)this.ViewContext.Controller).getalllocation(); 
    } 
<select name="select_item" id="select-sort" class="select__sort" tabindex="0"> 

       @for (int i=0;i<locations.Count;i++) 
       { 
        if((i==0)&&(ViewBag.location==null)) 
        { } 
       } 
     <option value="1" selected='selected'>@locations</option>//I need to display here 
       </select> 

現在,我無法顯示值,但數據是locations.Any想法?

+1

可怕的做法。創建一個屬性爲'string ID'和'string Name'的模型,並返回'List '。然後在視圖中使用'DropDownListFor()'來生成你的選擇。 –

+0

@StephenMuecke:你能告訴我任何例子嗎? –

+2

我強烈建議您轉到MVC網站並通過教程瞭解基礎知識。 –

回答

0

可以實現以下幫助:

@helper GenerateSelect(List<Dictionary<string, string>> dict) 
{ 
    foreach (var item in dict) 
    { 
     <option value="@item["id"]">@item["name"]</option> 
    } 
} 

,然後使用它:

<select name="select_item" id="select-sort" class="select__sort" tabindex="0"> 
    @GenerateSelect(locations)  
</select> 

然而,正如已經被其他人mentionted,是用字典有一個非常糟糕的做法預定義密鑰

您可以創建一個新的類:

public class Location 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

產生List<Location>:它

public List<Location> GetAllocation() 
{ 
    try 
    { 
     DataTable dt1 = new DataTable(); 
     string connString = cnst.cnstrin(); 
     string query = "SELECT * FROM `Mytable`.`location`"; 
     MySqlDataAdapter ma = new MySqlDataAdapter(query, connString); 
     DataSet DS = new DataSet(); 
     ma.Fill(dt1); 

     return dt1.AsEnumerable().Select(row => new Location { 
      Id = row["LocationId"], 
      Name = row["LocationName"] 
     }); 
    } 
    catch (MySqlException e) 
    { 
     throw new Exception(e.Message); 
    } 
} 

傳遞給你的查看模式,併產生select

@model List<Location> 

<select name="select_item" id="select-sort" class="select__sort" tabindex="0"> 
    @foreach (var loc in Model) 
    { 
     <option value="@loc.Id">@loc.Name</option> 
    } 
</select> 
+0

而不是使用List >,你可以建議他使用List >。如果只包含一個項目,Dictionary有什麼用? – sachin

+0

@sachin檢查我的更新:) –

+0

更好,謝謝! – sachin