第一個MVC模式的程式

來源:互聯網
上載者:User

標籤:style   blog   http   color   get   使用   

資料庫

是一個SQL sever資料庫,結構很簡單,建立名為firstMVC的資料庫,只包含一個資料表(名稱為Persons),其中共有三列,分別用於儲存人員(persons)的ID、姓名以及建立日期:

資料庫資訊:

模型

需要一個資料模型與資料庫進行通訊並處理資料。使用LINQ to SQL 從資料庫檢索資料。
在Model檔案夾添加一個新的LINQ to SQL項目條目,並將其名稱指定為Persons。然後串連資料庫,拖動Persons資料表,將其從伺服器總管拖動到LINQ to SQL設計器,結果

控制器

建立控制器,作為模型(資料)與視圖(使用者介面)之間的橋樑。建立一個新的名為PersonsController的控制器,該控制器有兩個動作方法:Index和IndividualPerson。第一個方法處理人員索引請求,第二個方法處理單個人員請求。
代碼如下:

using firstMVC.Models;using System.Linq;using System.Web.Mvc;namespace firstMVC.Controllers{    public class PersonController : Controller    {        //        // GET: /Person/        public ActionResult Index()        {            ViewData["Message"] = "Person List";            PersonsDataContext dataContext=new PersonsDataContext();            ViewData["Persons"] = dataContext.Persons.ToList();            return View();        }        public ActionResult IndividualPerson(int id)  //注意將ActionResult對象作為傳回值的方法的書寫名字是否與視圖名字一樣;        {            //注意:Persons是表的名字,Where要區分大小寫            PersonsDataContext dataContext=new PersonsDataContext();            Persons person = dataContext.Persons.Where                     (o => o.ID == id).Single();            ViewData["PersonName"] = person.Name;            ViewData["Person"] = person;            return View();        }    }}
視圖


建立視圖以顯示從控制器返回給終端使用者的資料。需要建立一個主版頁面和兩個視圖:網站主版頁面、Index視圖和IndividualPerson視圖。

 

Site.Master檔案

 

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %><!DOCTYPE html><html><head runat="server">    <meta name="viewport" content="width=device-width" />    <title>        <asp:ContentPlaceHolder ID="TitleContent" runat="server" />    </title></head><body>    <div class="page">        <div id="header">            <div id="title">                <h1>Getting Started                </h1>            </div>            <div id="menucontainer">                <ul id="menu">                    <li>                        <%= Html.ActionLink("Home","Index","Home")%>                    </li>                </ul>            </div>        </div>        <div id="main">            <asp:ContentPlaceHolder ID="MainContent" runat="server" />            <div id="footer">                Wrox Beginning ASP.NET MVC            </div>        </div>    </div></body></html>

 

Index視圖

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Site.Master" Inherits="System.Web.Mvc.ViewPage" %><asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server"></asp:Content><asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">    <h2>        <%= Html.Encode(ViewData["Message"]) %>    </h2>    <p>        <%            IList<firstMVC.Models.Persons> persons = ViewData["Persons"] as IList<firstMVC.Models.Persons>;            if (persons != null)            {        %>        <ul>            <% foreach (firstMVC.Models.Persons person in persons)               {            %>            <li>                <a href="/person/<%= Html.Encode(person.ID) %>">                    <%=Html.Encode(person.Name) %>                </a>            </li>            <% } %>        </ul>        <% } %>    </p></asp:Content>

 

IndividualPerson視圖

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Site.Master" Inherits="System.Web.Mvc.ViewPage" %><asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">    <%= Html.Encode(ViewData["PersonName"])%></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    <h2>        <%= Html.Encode(ViewData["PersonName"]) %>    </h2>    <p>        <%            firstMVC.Models.Persons person = ViewData["Person"] as firstMVC.Models.Persons;            if (person != null)            {        %>        <p>            Name:        <%=Html.Encode(person.Name) %>        </p>        <p>            Date Added:            <%= Html.Encode(person.DateAdded)%>    </p>        <% } %></asp:Content>

 

路由


已經在資料模型中完成了從資料庫檢索資料的操作,並編寫了控制器程式以擷取這些資料,將其傳遞到視圖。然而,在運行應用程式前,還需要將URL串連到控制器中的相應動作方法,現在,僅在名為Global.asax的ASP.NET應用程式類檔案中定製URL路由。

該類中有一個RegisterRoutes靜態方法,該方法有一個RouteCollection參數,該參數是定義路由並將它們添加到該集合的恰當位置。

該執行個體建立了兩個路由:一個用於索引頁面,另一個用於單個人員頁面。

using System.Web.Http;using System.Web.Mvc;using System.Web.Routing;namespace firstMVC{    // 注意: 有關啟用 IIS6 或 IIS7 傳統模式的說明,    // 請訪問 http://go.microsoft.com/?LinkId=9394801    public class MvcApplication : System.Web.HttpApplication    {        public static void RegisterRoutes(RouteCollection routes)        {            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");            //Index            routes.MapRoute(                "Default",                "",                new {Controller = "Person", Action = "Index"}                );            //IndividualPerson            routes.MapRoute(                "IndividualPerson",                "person/{id}",                new {Controller = "Person", Action = "IndividualPerson"}                );        }        protected void Application_Start()        {            RegisterRoutes(RouteTable.Routes);           // RouteConfig.RegisterRoutes(RouteTable.Routes); //引用RouteConfig檔案                                }    }}


測試應用程式:

選擇開始執行(不調試),顯示索引頁面:

 

通過單擊人員的姓名,就可以跳轉到人員頁面查看其資訊:

單擊張三

點擊李四

通過這個執行個體,分析各組件如何協同工作。

首先請求索引頁面,該請求與PersonController中的Index動作方法的模式相匹配,因此會將請求路由到PersonController中的Index動作方法,該方法載入所有人員列表,並將其傳遞給Index視圖,該視圖是顯示人員列表的地方。

當單機某個人員姓名時,請求URL和IndividualPerson動作方法模式相匹配,從而將請求路由到該動作方法沒改動作方法根據人員ID檢索人員的資訊,然後將檢索的資訊傳遞到IndividualPerson視圖進行顯示。

該操作流程圖為:

這種MVC形式被稱為“被動視圖”

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.