2014-03-07 65 views
0

我有兩個數據包"ViewBag.workSheetNames""ViewBag.selectedName"在Html5中顯示選定的下拉列表的價格

"ViewBag.workSheetNames"包含下拉菜單的選項值和"ViewBag.selectedName"包含必須在下拉菜單中顯示爲選中的名稱。我正在使用給定的代碼:

@foreach (var item in ViewBag.workSheetNames) 
     { 
     if (item == ViewBag.selectedName) 
     { 
      <option selected="selected">@item</option> 
     } 
     else 
     { 
      <option>@item</option> 
     }  
     } 

請建議任何有效的方法來做同樣的事情。

回答

0

您可以使用Mvc本身的HtmlHelpers來執行此操作。我制定了一個小例子:

@{ 
    ViewBag.SelectedItem= "2"; 
    ViewBag.List = new SelectList(
     new List<object>() 
     { 
      new {Id = 1, Label = "option 1"}, 
      new {Id = 2, Label = "option 2"} 
     }, "Id", "Label", ViewBag.SelectedItem); 
} 

@Html.DropDownList("DropdownListId", (SelectList)ViewBag.List) 
相關問題