ASP.NET MVC ビューでは、渡すモデルに厳密に型指定する必要があります。したがって、あなたの場合、UserModels
インスタンスをビューに渡しています。既にマスター ページがあり、テーブルに従業員のリストを表示すると仮定すると、次のような内容が考えられます。
<%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AppName.Models.UserModels>"
%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<table>
<thead>
<tr>
<th>Name</th>
<th>Sex</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<% foreach (var employee in Model.EmployeeList) { %>
<tr>
<td><%= Html.Encode(employee.name) %></td>
<td><%= Html.Encode(employee.sex) %></td>
<td><%= Html.Encode(employee.email) %></td>
</tr>
<% } %>
</tbody>
</table>
</asp:Content>
EmployeeList
さらに良いことに、コレクション プロパティ ( ~/Views/Shared/DisplayTemplates/GetEmployee.ascx
)の各項目に対して自動的にレンダリングされる再利用可能な表示テンプレートを定義します。
<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<dynamic>"
%>
<tr>
<td><%= Html.DisplayFor(x => x.name) %></td>
<td><%= Html.DisplayFor(x => x.sex) %></td>
<td><%= Html.DisplayFor(x => x.email) %></td>
</tr>
次に、メイン ビューでこのテンプレートを参照します。
<%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AppName.Models.UserModels>"
%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<table>
<thead>
<tr>
<th>Name</th>
<th>Sex</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<%= Html.EditorFor(x => x.EmployeeList)
</tbody>
</table>
</asp:Content>
これでループは不要になりforeach
(プロパティが標準の命名規則に従ったコレクション プロパティである場合、ASP.NET MVC は表示テンプレートを自動的にレンダリングするため)、モデルの再利用可能な表示テンプレートも用意されています。