ASP.NET MVC:DropDownListFor不选择任何选项

我有这个填充ASP.NET MVC视图中的下拉列表。

 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, })) %> 

调试这个我可以看到Selected属性应该设置为true 。 但是,在呈现视图时,列表中的所有选项都未被选中。 我意识到这可以通过DropDownListFor另一个重载完成,但我真的想让这个版本工作。

有任何想法吗?

您选择的值不起作用的原因是您使用Urls作为选项值,但在Selected子句中指定Model.ID

试试这样:

 <%= Html.DropDownListFor( model => model.Bikes, new SelectList(Model.Bikes, "Id", "Name", Model.ID) )%> 

"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) )%> 

你会注意到我已经颠倒了Name和Id,因为使用模型Id作为选项值似乎更合乎逻辑。


更新:

这不起作用的原因是因为您绑定到IEnumerableDropDownListFor帮助器的第一个参数)。 当你使用相同的model.Bikes时它应该是一个标量属性。 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, } )) %> 

关于不使用Urls作为选项值的说法是正确的。

我对这个概念有很多麻烦。 当您无法从包含该对象的属性的模型中传递“name”属性时,它尤其会显示自身,因为此类对象名称会自动添加到名称之前。 这太疯狂了。 在浪费了很多时间试图弄清楚这个之后我就放弃并编写了我自己的Drop-Down扩展,我在这里发布了。 它非常简单,工作得很好。

  public static MvcHtmlString SimpleDropDown(this HtmlHelper helper, object attributes, IEnumerable items, bool disabled = false) { XElement e = new XElement("select", items.Select(a => { XElement option = new XElement("option", a.Text); option.SetAttributeValue("value", a.Value); if (a.Selected) option.SetAttributeValue("selected", "selected"); return option; }) ); if (attributes != null) { Dictionary values = (from x in attributes.GetType().GetProperties() select x).ToDictionary(x => x.Name, x => (x.GetGetMethod().Invoke(attributes, null) == null ? "" : x.GetGetMethod().Invoke(attributes, null).ToString())); foreach(var v in values) e.SetAttributeValue(v.Key, v.Value); } if (disabled) e.SetAttributeValue("disabled", ""); return new MvcHtmlString(e.ToString()); } 

此外,我将标志禁用作为额外的参数,因为如果你想通过标准的匿名属性列表绑定它,它可能是一个非常麻烦。

以下是我目前如何使用它的示例。 我将字典翻译成SelectListItem列表,但它可以只是一个简单的列表。

 @Html.SimpleDropDown(new { id="EOM", name = "EOM", @class = "topBox" }, Model.EOM.Select(x => new SelectListItem { Text = x.Value, Value = x.Key.ToString(), Selected = Model.EOM.Selected == x.Key }), !Model.EOM.Available)