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

ASP.NET MVC传递对象数组至视图遍历时报CS1579错误求助

解决ASP.NET MVC视图遍历ViewData传递的对象数组报错问题

错误原因

ViewData存储的Object[]数组取出时默认是object类型,foreach无法直接遍历非枚举类型的object;同时匿名类型的成员在视图中无法被编译器识别,直接访问会有问题。

解决方案

方案1:强转数组+dynamic访问成员

在视图中将ViewData取出的对象强转为Object[],并用dynamic遍历访问匿名类型成员:

@{ 
    var cols = ViewData["TableColumns"] as Object[];
}
<div id="data_table">
    <table class="table" id="listview-table">
        <thead>
            <tr>
                @foreach (dynamic item in cols ?? Array.Empty<object>())
                {
                    <th>@item.name</th>             
                }
            </tr>
        </thead>
    </table>
</div>

注:?? Array.Empty<object>()是为了避免cols为null时引发空引用异常。

方案2:使用强类型ViewModel(推荐)

这种方式保证类型安全,编译器可提前检查错误,更利于项目维护。

  1. 定义列类型实体类:
public class TableColumn
{
    public string Data { get; set; }
    public string Name { get; set; }
}
  1. 修改控制器代码,使用强类型数组:
public async Task<ActionResult> IndexJson()
{
    TableColumn[] tableColumns = {
        new TableColumn { Data= "id", Name= "Id" },
        new TableColumn { Data= "code", Name= "Code" },
        new TableColumn { Data= "name", Name= "Name" },
        new TableColumn { Data= "colorCode", Name= "ColorCode" },
        new TableColumn { Name= "Actions" },
    };
    ViewData["TableColumns"] = tableColumns;
    // 更推荐:创建ViewModel类包含TableColumns,然后视图使用@model YourNamespace.YourViewModel
    return View("IndexJson");
}
  1. 视图中强转并遍历:
@{ 
    var cols = ViewData["TableColumns"] as TableColumn[];
}
<div id="data_table">
    <table class="table" id="listview-table">
        <thead>
            <tr>
                @foreach (var item in cols ?? Array.Empty<TableColumn>())
                {
                    <th>@item.Name</th>             
                }
            </tr>
        </thead>
    </table>
</div>

方案3:用ViewBag简化语法

控制器中改用ViewBag传递:

public async Task<ActionResult> IndexJson()
{
    Object[] tableColumns = {
        new { data= "id", name= "Id" },
        new { data= "code", name= "Code" },
        new { data= "name", name= "Name" },
        new { data= "colorCode", name= "ColorCode" },
        new { name= "Actions" },
    };
    ViewBag.TableColumns = tableColumns;
    return View("IndexJson");
}

视图中处理方式和方案1类似:

@{ 
    var cols = ViewBag.TableColumns as Object[];
}
<div id="data_table">
    <table class="table" id="listview-table">
        <thead>
            <tr>
                @foreach (dynamic item in cols ?? Array.Empty<object>())
                {
                    <th>@item.name</th>             
                }
            </tr>
        </thead>
    </table>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:32:17