2015-12-17 136 views
0

我從項目列表創建了一個表視圖,並且我在每行中都有一個DropDownListFor來從另一個列表中選擇值。我想映射每個名稱與相應的代碼。如果某些名稱已經完成映射,我如何顯示一些具有選定值的DropdownLists? 謝謝。MVC multiple DropDownListFor

<table class="table"> 
<tr> 
    <th> 
     @Html.DisplayNameFor(model => model.Name) 
    </th> 
    <th> 
     @Html.DisplayNameFor(model => model.Code) 
    </th> 
</tr> 

@foreach(var item in Model) 
{ 
    <tr> 
     <td> 
      @Html.DisplayFor(x => item.Name) 
     </td> 
     <td> 
      @Html.DropDownListFor(x => item.Code, (SelectList)ViewBag.SelectCodes) 
     </td> 
    </tr> 
    } 

+0

這是在你提交的表單中(你不能使用'foreach'循環來生成表單控件)? –

+0

我想我可以提交如果我使用(int i = 0; ...)循環 – albert

+0

是的,你需要一個'for'循環 - '@ Html.DropDownListFor(m => m [i] .Code .. .'如果你想提交一個表單,當在循環中使用'DropDownListFor()'時,你需要在每次迭代中產生一個新的'SelectList'(它是助手的一個不幸的限制),但另一種選擇是'EditorTemplate ' –

回答

0

首先,如果這種觀點是一種形式的一部分,您提交給控制器的方法,那麼你就需要使用for循環或EditorTemplate您的機型。您的foreach循環正在生成重複的name屬性,這些屬性與您的模型沒有任何關係,並且還會生成重複的id屬性,該屬性是無效的html。

不幸的是@Html.DropDownListFor()在循環中呈現控件時其行爲與其他幫助程序略有不同,並且必須在每次迭代中生成新的SelectList並設置Selected屬性。使用for循環視圖需要爲(模型必須IList<T>

@for(int i = 0; i < Model.Count; i++) 
{ 
    @Html.DropDownListFor(m => m[i].Code, new SelectList(ViewBag.SelectCodes, "Value", "Text", Model[i].Code)) 
} 

注意這是基於ViewBag.SelectCodes已經是一個SelectList,這是不是真的有必要。它可能類似於new SelectList(ViewBag.SelectCodes, "ID", "Name", Model[i].Code),其中SelectCodes是包含屬性IDName的對象的集合。

更好的選擇是爲您的模型使用自定義EditorTemplate。假設你的模型MyModel.cs,然後創建在/Views/Shared/EditorTemplates/MyModel.cshtml的局部視圖

@model MyModel 
<tr> 
    <td>@Html.DisplayFor(m => m.Name)</td> 
    <td>@Html.DropDownListFor(m => m.Code, (SelectList)ViewData["SelectCodes"])</td> 
</tr> 

在主視圖

@model IEnumerable<MyModel> 
.... 
<table> 
    <thead> 
     .... 
    </thead> 
    <tbody> 
     @Html.EditorFor(m => m, new { SelectCodes = ViewBag.SelectCodes }) 
    </tbody> 
</table> 

EditorFor()方法是然後(模板的名稱必須的類的名稱相匹配)使用AdditionalViewDataSelectList傳遞給模板,該方法將正確地爲集合中的每個項目生成html,而不必生成新的SelectList's。