Den*_*gan 5 c# linq asp.net-mvc html.dropdownlistfor drop-down-menu
我有这个填充ASP.NET MVC视图中的下拉列表.
<%= Html.DropDownListFor(model => model.Bikes,
Model.Bikes.Select(
x => new SelectListItem {
Text = x.Name,
Value = Url.Action("Details", "Bike", new { bikeId = x.ID }),
Selected = x.ID == Model.ID,
})) %>
Run Code Online (Sandbox Code Playgroud)
调试这个我可以看到该Selected属性设置为true应该的时间.但是,在呈现视图时,列表中的所有选项都未被选中.我意识到这可以通过另一个重载完成,DropDownListFor但我真的想让这个版本工作.
有任何想法吗?
您选择的值不起作用的原因是您使用Urls作为选项值,但Model.ID在Selected子句中指定.
试试这样:
<%= Html.DropDownListFor(
model => model.Bikes,
new SelectList(Model.Bikes, "Id", "Name", Model.ID)
)%>
Run Code Online (Sandbox Code Playgroud)
"Id"表示将用作选项值"Name"的属性,同时指示将用作选项标签的属性.
如果你想保留Url.Action你可以尝试:
<%= Html.DropDownListFor(
model => model.Bikes,
new SelectList(Model.Bikes.Select(x => new {
Id = x.Id,
Name = Url.Action("Details", "Bike", new { bikeId = x.ID })
}), "Id", "Name", Model.ID)
)%>
Run Code Online (Sandbox Code Playgroud)
你会注意到我已经颠倒了Name和Id,因为使用模型Id作为选项值似乎更合乎逻辑.
更新:
这不起作用的原因是因为你绑定了一个IEnumerable(帮助器的第一个参数DropDownListFor).当您使用相同的model.Bikes集合时,它应该是标量属性:
<%= Html.DropDownListFor(
model => model.SelectedBikeValue,
Model.Bikes.Select(
x => new SelectListItem {
Text = x.Name,
Value = Url.Action("Details", "Bike", new { bikeId = x.ID }),
Selected = x.ID == Model.ID,
}
)) %>
Run Code Online (Sandbox Code Playgroud)
关于不使用Urls作为选项值的说法是正确的.
| 归档时间: |
|
| 查看次数: |
5251 次 |
| 最近记录: |