我的页面上有很多 DropDownList
class BigViewModel
{
public List<SmallViewModel> SmallVM {get;set;}
public List<SelectListItem> Items {get;set;}
//some other properties
}
class SmallViewModel
{
public string ItemId {get;set;}
//some other properties
}
<table>
@for( var i = 0;i<Model.SmallVM.Count();i++)
{
<tr>
<td>
@Html.DropdownListFor(m=> m.SmallVM.ItemId, Model.Items)
</td>
</tr>
}
//display other properties
</table>
在控制器中
bigViewModel.Items = List<SelectListItem>
{
new SelectListItem{Value = "1", Text = "aaa"},
new SelectListItem{Value = "2", Text = "bbb"},
new SelectListItem{Value = "3", Text = "ccc"},
}
bigViewModel.SmallVM = new List<SmallViewModel>
{
new SmallViewModel{ItemId = 3},
new SmallViewModel{ItemId = 2},
}
在控制器中我设置了不同的ItemId
对于每个 SmallVM 和每个 DropDownList 使用相同的Items
收藏。我想为每个 DropDownList 设置 SmallViewModel 的默认值。例如,在本例中,有两个 DropDownList,第一个应显示默认文本“ccc”,第二个应显示“bbb”。
我应该放不同的List<SelectedListItem>
为每个 SmallViewModel 并设置它们 Selected 属性还是有其他方法?
此行为已被报告为 CodePlex 上的错误,但尚未修复。使用DropDownListFor()
in a for
循环未正确绑定,并且无论属性值如何,始终选择第一个选项。为了DropDownListFor()
为了在使用集合时正确工作,您需要使用EditorTemplate
对于模型。
In /Views/Shared/EditorTemplates/SmallViewModel.cshtml
@model SmallViewModel
@Html.DropdownListFor(m => m.ItemId, (SelectList)ViewData["Items"])
然后在主视图中
@model BigViewModel
@using(Html.BeginForm())
{
// Pass the select list to the EditorTemplate as addtionalViewData
@Html.EditorFor(m => m.SmallVM, new { Items = Model.Items })
<input type="submit" />
}
你现在应该有 2<select>
控件分别显示“ccc”和“bbb”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)