【问题标题】:ASP.NET MVC DropDownListFor doesn't set selected data to true in ListASP.NET MVC DropDownListFor 未在列表中将选定数据设置为 true
【发布时间】:2015-11-12 22:47:32
【问题描述】:

我有一个视图,它的模型是 IEnumerable。我在 foreach 循环中使用 DropDownListFor Html 帮助器来输出下拉列表。但它不会将所选项目设置为 true。代码如下:

@model IEnumerable<Example>
@foreach (var item in Model) {
    @Html.DropDownListFor(modelItem => item.FilePath, (IEnumerable<SelectListItem>)ViewBag.ConfigFiles, string.Empty, null)
}

上面的代码输出一个 Html 选择元素。但即使 item.FilePath 与其中一个选项的值相同,也没有选择任何选项。

【问题讨论】:

  • 这是有道理的。谢谢@StephenMuecke

标签: c# asp.net asp.net-mvc html-helper html.dropdownlistfor


【解决方案1】:

这是在循环中使用DropDownListFor() 的不幸限制,您需要在每次迭代中生成一个新的SelectList。但是,您使用foreach 循环来生成表单控件将不起作用。它创建与您的模型无关的重复name 属性因此不会绑定,并且它还会生成无效html 的重复id 属性。

将您的模型更改为IList&lt;T&gt; 并使用for 循环并在每次迭代中使用设置selectedValue 的构造函数生成一个新的SelectList

@model IList<Example>
....
@for(int i = 0; i < Model.Count; i++)
{
  @Html.DropDownListFor(m => m[i].FilePath, new SelectList(ViewBag.ConfigFiles, "Value", "Text", Model[i].FilePath), string.Empty, null)
}

请注意,这现在会生成绑定到您的模型的 name 属性

<select name="[0].FilePath">....<select>
<select name="[1].FilePath">....<select>
.... etc

请注意,无需在控制器中创建IEnumerable&lt;SelectListItem&gt;。您可以改为将对象集合分配给 ViewBag

ViewBag.ConfigFiles = db.ConfigFiles;

在视图中

new SelectList(ViewBag.ConfigFiles, "ID", "Name") // adjust 2nd and 3rd parameters to suit your property names

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多