为了使视图与您从操作传递给它的对象无缝集成,您需要更改位于视图顶部的Inherits=
属性。@Page directive
确保通过以下方式将此对象从操作传递到视图:
public MyController : Controller
{
public ActionResult ShowResults()
{
List<Result> results = GenerateResults();
return View(results); // this passes 'results' as the model of the view
}
}
在这种情况下,您有一个名为的自定义对象Result
,您将一个列表传递给视图。所以在@Page
指令中你Inherits=
将
Inherits="System.Web.Mvc.ViewPage<List<MyNameSpace.Models.Result>>"
所以你的完整@Page
指令看起来像这样:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<MyNameSpace.Models.Result>>" %>
这样做是告诉View
你Model
是 type List<MyNameSpace.Models.Result>
。
现在,在视图中,Model
对象将自动转换为类型List<MyNameSpace.Models.Result>
,因此您可以无缝且干净地执行以下操作。
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<MyNameSpace.Models.Result>>" %>
<table>
<tr>
<th>Result PropertyOne</th>
<th>Result PropertyTwo</th>
</tr>
<% foreach(var result in Model){ %>
<tr>
<td><%: result.PropertyOne %></td>
<td><%: result.PropertyTwo %></td>
</tr>
<% } %>
</table>