在foreach中绑定DropDownListFor.净MVC

本文关键字:MVC DropDownListFor 绑定 foreach | 更新日期: 2023-09-27 18:07:12

下面是我的代码:

视图模型

public class FooViewModel{
   public Guid BarId { set;get }
}

视图:

@model IEnumerable<FooViewModel>
@foreach (var c in Model)
{
    <div>
        @Html.DropDownListFor(o => c.BarId , (List<SelectListItem>)ViewBag.BarCollection)
    </div>
}

问题是DropDownListFor完全创建了选项,但绑定不起作用。

在foreach中绑定DropDownListFor.净MVC

不能使用foreach循环为集合中的项生成控件。如果你检查html,你会看到你有重复的name属性没有索引(也复制id属性是无效的html)。对于FooViewModel,您需要一个自定义EditorTemplatefor循环。使用for循环(你的模型必须实现IList<T>)

@model IList<FooViewModel>
for (int i = 0; i < Model.Count; i++)
{
  @Html.DropDownListFor(m => m[i].BarId, ....)
}

注意html现在是

<select name="[0].BarId" ..>
<select name="[1].BarId" ..>

等。