< turn >asp. NET learning notes the understanding of MVC underlying operating mechanism

Source: Internet
Author: User
Tags actionlink

One of the ASP. NET MVC Architecture and Combat series: understanding the underlying operating mechanism of MVC

Today, I'm going to start a new topic: the ASP. NETMVC framework . First, we review the similarities and differences between ASP. NET Web Form and ASP. NET, and show their merits and demerits in the web domain. Before the discussion, I was very enthusiastic about both of these technologies, and I personally feel that in the actual project development, both can benefit us, so is the current web domain two major parallel and popular technology. As we all know, in the traditional ASP. NET Web form application, Microsoft has designed a more complete, concise development environment for us, and provides a complex processing engine, developers can simply drag and drop the control and write the corresponding event to achieve the function we want. However, because of these rapid development patterns, it is difficult for developers to understand the workings of HTML behind the program, and often the HTML and background programs are intertwined (although more advanced than the ASP), so that the responsibilities of page designers and developers are integrated, difficult to disassemble, Sometimes beginners to the mechanism of ASP. NET Web form, can lead to various misuse, such as viewstate storage of large amounts of data caused by page congestion, session cross-server load and lost, and other inexplicable problems, and difficult to find the root point of the problem. As a result, ASP. NET MVC comes into being, dividing the model, view and controller into different Web application modules, so that designers and developers have a better separation of responsibilities, and do not need to save the page view, no data callback, improve the maintainability and extensibility of the application, In particular, it is very easy to test-drive development.

Next, let's look at the three main components of MVC (models, views, controllers). The so-called model is the data source that MVC needs to provide, which is responsible for data access and maintenance. The so-called view is the user interface for displaying data in the model. The so-called controller, which is used to process the user input, is responsible for changing the state of the model and selecting the appropriate view to display the model's data. Here is a diagram of the interaction between the three major components of MVC that I have drawn.

As can be seen from the interaction diagram, MVC has undergone five steps, from the user sending the request to the page rendering results, as follows: (1). The user enters the address in the browser, sends the request to the page (but actually sends the command to the Controller); (2). After the controller accepts the command, it requests the relevant data to the model; (3). The model returns the corresponding data to the controller; (4). The controller sends the relevant data to the specified view; (5). The specified view renders the relevant data. From these five steps, it is not difficult to find that the controller plays a central role in the nexus, the responsibilities become more clear, which is the main focus of the developer components. Next, I use practical examples to illustrate the MVC interaction process, and to give detailed theoretical support. We take the Northwind Categories table as an example, step by step to show the category of additions and deletions to find out how the implementation process in MVC. After you create a new ASP. NET MVC2 application, the following interface is displayed.

As can be seen from the interface, Microsoft has agreed a set of canonical directory structure, below I summarize each directory:

Content: Storing static resource files such as CSS and images.

Controllers: Stores a series of ***controllers-named controller components that perform interactions with models and views (the general business is extracted into the business logic layer).

Models: A model component, such as LINQ to SQL or the ADO data Entity model, that can also hold information about its operations (typically extracted into the data access layer).

Scripts: The JavaScript file that the application must be stored in.

Views: Store and controllers in the view corresponding to the method, note: If there is a ***controllers controller, it is necessary to map a named folder in views. Shared under Views stores the public parts of the view component, such as. master, style sheets, and so on.

In addition, Global.asax implements the URL of the MVC route control, in which the default route can be set in RegisterRoutes (), the following is the specific route code for global.asax.

public class mvcapplication:system.web.httpapplication{public    static void RegisterRoutes (RouteCollection routes )    {        //can be ignored for routing configuration        routes. Ignoreroute ("{resource}.axd/{*pathinfo}");        Sets the default route        routes. MapRoute (            "Default",//route name            "{controller}/{action}/{id}",//URL with parameter            new {controller = "Home", action = "I Ndex ", id = urlparameter.optional}//parameter default value        );    }    protected void Application_Start ()    {        arearegistration.registerallareas ();        RegisterRoutes (routetable.routes);    }}

When MVC is in. Net When running in framework3.5, you also need to register the UrlRoutingModule class in the HttpModules configuration section in Web. config to resolve URL routing, which is the fundamental difference between MVC and traditional ASP.

How does the UrlRoutingModule module translate the page request into a URL route and invoke the method in the controller to implement the view?

(1). When the MVC site is launched, the URL address entered by the user is first passed to the UrlRoutingModule module, which resolves the URL and selects the corresponding URL route, and obtains the corresponding Ihttpcontext object to handle the URL route. By default, the Ihttpcontext object is the Mvchandler object that selects the relevant controller to handle the user's request. That is, the UrlRoutingModule module and the Mvchandler object are the entry point of the MVC website, the main implementation: select the corresponding controller, instantiate the controller object, call the controller related methods. The following table describes the execution of page requests in more detail.

(2). In a traditional ASP. NET application, each request page corresponds to a file system, which is actually a class that implements the IHttpHandler interface, which invokes the ProcessRequest () method whenever the page makes a request. Returns the specified content to the browser. In an MVC-based application, each request page is mapped to a corresponding controller-related method, and the controller is responsible for returning the relevant content to the browser. It is necessary to note that the same controller can contain multiple methods to map multiple pages. The page-to-controller mapping is implemented through the path table (routetable.routes), where the corresponding routing object is added to the path table to map URLs with the {controller}/{action}/{id} pattern to Mvcroutehandler. When you request an MVC page, The UrlRoutingModule module in the Web. config configuration file resolves the URL and gets the associated Routedata object to create the HttpHandler instance Mvchandler, and then Mvchandler in the call ProcessRequest The () method creates an instance of the controller, executes the controller's execute () method, and specifies the view () method to invoke by the reflection mechanism to push the page content to the browser.

Next, I'll build the model based on the new MVC application I just created to implement the application's data access and business logic (this is just a demo, not for real project development). On the Models folder, add ADO. NET Entity Data model and configure the associated connection (take NORTHWIND.EDMX as an example), select the Categories table, and the operation should be as follows.

Then we switched to the controller directory, and just now we talked about the controller routing the URL of the user request to a related method instead of a real file in the file system. To open the default "HomeController.cs" file:

Indicates that a friendly error page will open when an error occurs when executing the Controller method [the handleerror]//controller must be named "***controllers" and implemented by the controllers or Icontrollerpublic class    the method in the homecontroller:controller{//controller must be public, and if it is an internal method, it will be set to [Nonactionattribute] public    ActionResult Index ()    {        //Set the dictionary data to pass the specified data to the view        viewdata["Message"] = "Welcome, miracle!";        Returns the specified content to the browser in        return View ();}    }

We modify HomeController.cs to implement categories display, edit, add, and detail pages that correspond to the relevant action methods index (), edit (), Create (), and details ().

public class homecontroller:controller{//Instantiate Data entity object private Northwind db = new Northwind (); The data shows public ActionResult Index () {var model = db.        Categories.tolist ();    return View (model); }//Edit [Acceptverbs (Httpverbs.get)] public actionresult edit (int id) {var model = db.        Categories.first (c = C.categoryid = = ID);    return View (model); } [Acceptverbs (Httpverbs.post)] public actionresult Edit (int id, formcollection form) {var model = db.        Categories.first (c = C.categoryid = = ID);        Updatemodel (model, new[] {"CategoryName", "Description"}); Db.        SaveChanges ();    Return redirecttoaction ("Index");        }//Create [Acceptverbs (httpverbs.get)] public ActionResult Create () {var model = new Categories ();    return View (model); } [Acceptverbs (Httpverbs.post)] public actionresult Create (int id, formcollection form) {var model = DB.C Ategories. FirstOrDefault (c =&GT        C.categoryid = = ID);            if (model = = NULL) {var cate = new Categories ();            Updatemodel (Cate, new[] {"CategoryName", "Description"}); Db.            Addtocategories (Cate); Db.            SaveChanges ();        Return redirecttoaction ("Index");        } else {return redirecttoaction ("Create"); }}//Details [Acceptverbs (httpverbs.get)] public actionresult details (int id) {var model = db.        Categories.first (c = C.categoryid = = ID);    return View (model); }}

From the above method we see that the return type is the ActionResult class, in fact, this is an abstract class, the actual return is a subclass of ActionResult.

Careful friends may find that Edit, create are in a pair of ways to appear, so what is the point? Looking down again, it's not hard to find one using GET, the other using post. In other words, we will first get this data before editing and submit it to the server. Create uses a Get method to open a page that has no value, populates the corresponding value, and then submits it to the server. Such a thought, it is not much easier. With the controller, next, we start to create a view of the Controller method, the operation is very simple: Click the Controller method name right-click "Add View", will be corresponding to the views of the corresponding folder (name for the controller) to establish the corresponding page (name is the method name). First create the index view (you need to select the strongly typed view MVCDemo.Models.Categories) and the view contents as list, the code is as follows:

<%@ page title= "" Language= "C #" masterpagefile= "~/views/shared/site.master" inherits= "System.Web.Mvc.ViewPage <IEnumerable<MVCDemo.Models.Categories>> "%><asp:content id=" Content1 "contentplaceholderid=" Titlecontent "runat=" Server "> Index</asp:content><asp:content id=" Content2 "contentplaceholderid="            MainContent "runat=" Server > 

In this page, we find that there are many places where <%***%> contains code, and HTML, a built-in class that contains many methods for creating controls. Here ActionLink (linktext,actionname,params) is used to create the link, LinkText is the link text, ActionName is the controller's method name, and the params is the parameter list. Create edit, new, and detail pages in the same way. Here I no longer discuss, can be downloaded in the source code . The only thing that needs to change is to select the corresponding view content (Edit, Create, Details). Here, there is a basic understanding of MVC, if you are not familiar with it, you can try to open the source code to carefully analyze it.

< turn >asp. NET learning notes the understanding of MVC underlying operating mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.