0

asp.net mvc 2.0 は初めてです。asp.net mvc を使用してデータベースからデータを一覧表示する方法について質問があります。

コントローラ

public ActionResult ListEmployee() {
       UserModels emp = new UserModels();
        emp.EmployeeList = (List<tblEmployee_Employee>)Session["list"];
        return View(emp);
}

モデル

 public class GetEmployee
{
    public string name { get; set; }
    public string sex { get; set; }
    public string email { get; set; }
}   

ビュー ページの employee.aspx ページがありますが、このビュー ページにコードを記述する方法がわかりません。

この問題を解決するのを手伝ってください。

ありがとう、

4

1 に答える 1

0

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 は表示テンプレートを自動的にレンダリングするため)、モデルの再利用可能な表示テンプレートも用意されています。

于 2012-07-26T12:39:05.430 に答える