Bas*_*maa 3 asp.net-mvc asp.net-mvc-3
我需要从IEnumerable @model访问一个特定的项目;
我知道我可以通过以下代码到达所有项目:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.FoodName)
</td>
}
Run Code Online (Sandbox Code Playgroud)
但是我需要通过做类似的事情来访问第三个项目(例如):Model [3] .FoodName
有没有办法从MVC中的IEnumerable对象到达特定的索引项?
您可以使用ElementAt(index)
扩展方法:
Model.ElementAt(2)
Run Code Online (Sandbox Code Playgroud)
或者将模型类型更改IEnumerable<T>
为IList<T>
或T[]
:
@model IList<SomeViewModel>
Run Code Online (Sandbox Code Playgroud)
现在你可以用索引循环:
@for (var i = 0; i < Model.Count; i++)
{
@Html.DisplayFor(x => x[i].FoodName)
}
Run Code Online (Sandbox Code Playgroud)
如果生成输入字段(EditorFor,TextBoxFor,...),这是首选方法,因为这样将为它们分配正确的名称.
归档时间: |
|
查看次数: |
2117 次 |
最近记录: |