2012-07-26 65 views
0

我是新來的asp.net mvc 2.0.I有一個關於使用asp.net mvc從數據庫列出數據的問題。使用asp.net mvc 2.0列出數據庫中的所有數據

控制器

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頁面,但我不知道如何在這個視圖頁面編寫代碼。

請幫我解決這個問題。

感謝,

回答

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> 

,甚至更好,定義將automaticall被渲染爲可重複使用的顯示模板在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將自動呈現顯示模板),並且還有用於模型的可重用的顯示模板。

相關問題