如何在没有lambda表达式的情况下使用Html.DropDownListFor?

时间:2012-01-01 13:36:42

标签: asp.net-mvc asp.net-mvc-3

我有以下代码可以使用:

@for (var index = 0; index < Model.AdminSummaries.Count(); index++) {

   <div class="rep_td0" id="rk_@(index)">
      @Model.AdminSummaries[index].RowKey
   </div>
   <div class="rep_td0"> 
   @Html.DropDownListFor(
      x => x.AdminSummaries[index].Status, 
      new SelectList(
            AdminStatusReference.GetAdminStatusOptions(),
            "Value",
            "Text",
      ), 
      new { id = string.Format("Status_{0}", index) }
   )

我遍历Model.AdminSummaries,这是一种

public IList<AdminSummary> AdminSummaries { get; set; }

由于它是IList,我可以使用索引和x =&gt; x.AdminSummaries [index] .Status用于获取每行的正确状态,还有一个索引号,我可以用它来更改每行的项ID。

现在我遇到了问题。我想将相同的代码方法应用于以下,这是我的模型中具有类似于AdminSummaries字段的类(包括状态字段):

public ICollection<Item> Items { get; set; }

由于它是ICollection,我认为我无法使用[index]

访问元素

我可以使用foreach但是如何将状态值提供给DropDownListFor的第一个参数?另外,我如何获得索引值,以便我可以索引行中的字段。

更新

索引点是我在原始问题中添加的内容。重要的是,解决方案可以执行类似下面的操作,以便稍后我可以在表单字段上使用jQuery。

id="rk_@(index)"

1 个答案:

答案 0 :(得分:2)

您可以使用编辑器模板。因此,您可以使用以下内容替换此for循环:

@Html.EditorFor(x => x.Items)

然后定义编辑器模板,该模板将自动呈现给集合的每个元素(~/Views/Shared/EditorTemplates/Item.cshtml):

@model Item
<div class="rep_td0"> 
    @Html.DropDownListFor(
        x => x.SomePropertyOfItemToBindTo, 
        new SelectList(
            AdminStatusReference.GetAdminStatusOptions(),
            "Value",
            "Text",
            Model.SomePropertyOfItemToBindTo
        )
    )
</div>