アクションからビューに渡すオブジェクトとビューをシームレスに統合するには、ビューの上部にあるの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がタイプであることを伝えること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>