ASP.NET MVC:DropDownListFor不选择任何选项 [英] ASP.NET MVC: DropDownListFor doesn't select any option
问题描述
我有这样的填充一个下拉在ASP.NET MVC视图列表
I have this to populate a drop down list in an ASP.NET MVC view.
<%= 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,
})) %>
调试这个我可以看到选
属性设置为真正
当它应该是。但是,当视图显示,没有在列表中的选项被选择。我意识到,这可能是与 DropDownListFor
的另一个重载做,但我真的很想得到这个版本的工作。
Debugging this I can see that the Selected
property is set to true
when it should be. But when the view is rendered, none of the options in the list is selected. I realize that this could be done with another overload of DropDownListFor
but I really want to get this version working.
任何想法?
推荐答案
<击>您选择的价值不工作的原因是因为你使用URL作为选项值,但指定 Model.ID
的选
子句。
尝试是这样的:
<%= Html.DropDownListFor(
model => model.Bikes,
new SelectList(Model.Bikes, "Id", "Name", Model.ID)
)%>
ID
表示的属性,将作为期权的价值,而名称
表示将用作选项标签的属性。
"Id"
indicates the property that will be used as option value while "Name"
indicates the property that will be used as option label.
如果您要保留 Url.Action
你可以尝试:
If you want to preserve the Url.Action
you could try:
<%= 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)
)%>
您会发现,我倒名称和ID,因为它似乎更符合逻辑使用模型ID作为选项值。
击>
You will notice that I've inverted the Name and Id as it seemed more logical to use the model Id as option value.
更新:
这不工作的原因是因为你绑定到的IEnumerable
(即 DropDownListFor
助手的第一个参数)。当您使用的是相同 model.Bikes
收藏这应该是一个标量属性:
The reason this doesn't work is because you are binding to an IEnumerable
(the first argument of the DropDownListFor
helper). It should be a scalar property while you are using the same model.Bikes
collection:
<%= 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,
}
)) %>
我的话作为有关选项值代表真正不使用的URL。
My remark about not using Urls as option values stands true.
这篇关于ASP.NET MVC:DropDownListFor不选择任何选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!