2011-03-24 28 views
4

我有一个模型的列表属性foreach循环查看。现在,我希望能够让用户使用下拉列表设置列表中每个项目的值。但我不知道该怎么做。我用这样的事情时,它不是在foreach循环:在Asp.Net MVC视图中使用dropdownlist for foreach?

@Html.DropDownListFor(model => model.Level, new SelectList(new[] { 1, 2, 3, 4, 5 }, Model.Level)) 

但是我怎么做到这一点的时候,我需要引用item.Level在循环呢?这里是我查看代码:

<div id="formDiv"> 
    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" })) 
    { 
     @Html.ValidationSummary(true) 
     <fieldset> 
      <legend>Ny arbetserfarenhet</legend> 
      <table> 
       <tr> 
        @*<th></th>*@ 
        <th> 
         Program 
        </th> 
        <th> 
         Nivå 
        </th> 
       </tr> 
       @foreach (var item in Model) { 
        <tr> 
         <td> 
          @item.Program.Name 
         </td> 
         <td> 

          @item.Level 
         </td> 
        </tr> 
} 
      </table> 
     </fieldset> 
    } 
</div> 

回答

7

我有一个foreach循环的模式列表属性查看

我建议你避免在你的视图中编写循环来支持编辑器模板。所以:

@model IEnumerable<AppName.Models.ModelName> 
<div id="formDiv"> 
    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" })) 
    { 
     @Html.ValidationSummary(true) 
     <fieldset> 
      <legend>Ny arbetserfarenhet</legend> 
      <table> 
       <tr> 
        <th> 
         Program 
        </th> 
        <th> 
         Nivå 
        </th> 
       </tr> 
       @Html.EditorForModel() 
      </table> 
     </fieldset> 
    } 
</div> 

,并在相应的编辑器模板(~/Views/Shared/EditorTemplate/ModelName.cshtml):

@model AppName.Models.ModelName 
<tr> 
    <td>@Model.Program.Name</td> 
    <td> 
     @Html.DropDownListFor(
      model => model.Level, 
      new SelectList(
       Enumerable.Range(1, 5).Select(x => new { Value = x, Text = x }), 
       "Value", 
       "Text" 
      ) 
     ) 
    </td> 
</tr> 

所以编辑模板将被渲染为模型中的每个元素(这是某种类型的集合)。重要的部分是编辑器模板必须位于~/Views/Shared/EditorTemplates中,并命名为XXX.cshtml,其中XXX是您的主视图模型集合中使用的类型名称。

+0

感谢您的提示!是不是使用for循环的原因,它是这样更优雅,或者其他一些原因?我可以使用它,但必须将选择列表更改为我以前使用的语法,我在列表中列出了一些奇怪的值和文本,否则它的工作正常! – Anders 2011-03-25 09:54:03

+0

@Anders Svensson,原因很多:清晰的视图,较少的代码,强类型的帮助者,不需要担心生成正确的id和名字来绑定回来,... – 2011-03-25 11:05:46

+0

好的,谢谢!无论如何,我意识到我也必须对项目进行分类......这使得这一点变得更加复杂。如果您能够接受,欢迎您查看我的后续问题:http://stackoverflow.com/questions/5433710/group-a-collection-in-mvc-view-and-update- model-in-controller – Anders 2011-03-25 15:26:14

0

使用的语法如下:

@Html.DropDownListFor(model => model.Level, new SelectList(Model.level as System.Collections.IEnumerable, "VALUE_FIELD", "TEXT_FIELD", YOUR PROPERTY NAME) 
+0

这并不是说问题出在选择列表的,这是一个事实,即下拉列表是在foreach循环中,所以我不能使用模型=> model.Level语法... – Anders 2011-03-24 15:51:30

4

你试过:

@Html.DropDownListFor(m => item.Level, new SelectList(new[] { 1, 2, 3, 4, 5 }, item.Level)) 
0

MVC将创建循环。只需使用编辑器模板,特殊文件夹中的部分视图,其余部分就像魔术一样。

编辑模板

@model Models.AdditionalAccountingLine 
@Html.HiddenFor(m => m.IsRequired) 
@Html.DropDownListFor(m => m.FieldValue, new SelectList(@Model.FieldValueOptions, "Key", "Value"), "") 

查看

@Html.EditorFor(m => m.AdditionalAccountingLines);