You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET MVC视图中使用for循环访问模型列表数据

使用for循环在视图中访问控制器传递的列表数据

修正后的控制器代码

你的控制器代码存在几处语法错误,先修正如下:

List<ViewModel> list = new List<ViewModel>();
ViewModel model = new ViewModel();
// 正确初始化字符串数组
string[] str1 = { "My", "name", "is", "Md", "Mohtesham" };
model.a = str1[0];
model.b = str1[1];
model.c = str1[2];
model.d = str1[3];
model.e = str1[4];
// 调用List的Add方法(首字母大写)并添加分号
list.Add(model);
return View(list);

视图中用for循环遍历列表

不要固定循环次数,而是根据列表的实际长度遍历,通过索引访问每个元素的属性:

@model List<FD_Application.Models.ViewModel>
<table class="table table-bordered table-striped">
    <tr>
        <th>a</th>
        <th>b</th>
        <th>c</th>
        <th>d</th>
        <th>e</th>
    </tr>

    @for(int i = 0; i < Model.Count; i++) 
    { 
        <tr>
            <td>@Model[i].a</td>
            <td>@Model[i].b</td>
            <td>@Model[i].c</td>
            <td>@Model[i].d</td>
            <td>@Model[i].e</td>
        </tr>
    }
</table>

关键说明

  1. 控制器里字符串数组必须用双引号包裹元素,并用大括号初始化;List.Add方法首字母需大写,语句末尾加结束分号。
  2. 视图中通过Model[i]访问列表的第i个ViewModel对象,直接获取其属性值即可,循环条件用Model.Count保证遍历所有数据,而非固定的5次。

内容的提问来源于stack exchange,提问作者Mohtesham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:45:26