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

Controller传递List到View时,无法在视图中获取模型项求助

问题分析与解决方法

你的核心问题在于Controller的GetDetail方法直接返回了集合对象,ASP.NET MVC会自动将其序列化为JSON响应,而不是渲染你编写的View,所以View无法获取到模型数据。

解决方案:修改Controller方法返回View并传递模型

将GetDetail的返回类型改为ActionResult,并通过View()方法将模型传递给View,这样框架才会渲染指定的View并注入模型数据:

public ActionResult GetDetail()
{
    var employee = context.Employees
                          .Select(x => new EmployeeNameViewModel()
                           {
                               Id = x.Id,
                               Name = x.Name,
                               SurName = x.SurName,
                               Project = x.Projects.SingleOrDefault()
                           });
           
    var employeeList = employee.ToList<EmployeeNameViewModel>();
    return View(employeeList); // 将模型传递给View
}

额外检查点

  • 确保你的View文件(比如GetDetail.cshtml)放在正确的目录下:Views/[ControllerName]/GetDetail.cshtml,如果View名称不同,可以在View()方法中指定,比如View("MyViewName", employeeList)。
  • 确认Project实体的属性可以被正确序列化和传递,如果后续需要在View中展示Project的属性(比如@item.Project.Name),确保该实体的属性是公共可访问的,且没有循环引用问题(你的JSON中employee为null,已经避免了循环引用,这点没问题)。

修改后,访问该Action时,框架会渲染你的View并将模型数据注入,此时@foreach (var item in Model)就能正常遍历数据了。

内容的提问来源于stack exchange,提问作者Mustafa Şan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:22:08