我從項目列表創建了一個表視圖,並且我在每行中都有一個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>
}
這是在你提交的表單中(你不能使用'foreach'循環來生成表單控件)? –
我想我可以提交如果我使用(int i = 0; ...)循環 – albert
是的,你需要一個'for'循環 - '@ Html.DropDownListFor(m => m [i] .Code .. .'如果你想提交一個表單,當在循環中使用'DropDownListFor()'時,你需要在每次迭代中產生一個新的'SelectList'(它是助手的一個不幸的限制),但另一種選擇是'EditorTemplate ' –