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