[英]ASP.NET MVC: DropDownListFor doesn't select any option when rendered
[英]ASP.NET MVC: DropDownListFor doesn't select any option
我用它来填充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,
})) %>
对此进行调试,可以看到应该将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作为选项值似乎更合逻辑。
更新:
这不起作用的原因是因为您绑定到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, } )) %>
我关于不使用Urls作为选项值的说法是正确的。
我对这个概念有很多麻烦。 当您无法从对象中包含该属性的模型中传递“名称”属性时,它会特别显示出来,因为此类对象名称会自动添加到名称中。 这太疯狂了。 在花了很多时间试图弄清楚这一点之后,我放弃了,写了我自己的Drop-Down扩展,并在这里发布。 这非常简单,效果很好。
public static MvcHtmlString SimpleDropDown(this HtmlHelper helper, object attributes, IEnumerable<SelectListItem> 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<string, string> 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.