Basic ASP. net mvc knowledge

Source: Internet
Author: User
Tags actionlink

Edit recommendation 《ASP. net mvc video tutorial"

One penguin first discovered that the Earth was warming and the iceberg was melting. When he came back to tell other penguins, none of them were willing to believe it, because they thought they were living well now, I don't want to worry about how to change or when changes will come, so I still do routine work every day and don't want to study others' opinions. 「 Sometimes people will resist changes, but they just don't want to change. But they are technicians who are willing to accept new ideas. They usually live for a long time 」.

On the Internet, we can see some netizens mistakenly think that MVC and 3-Tier (three-Tier architecture) are similar:

Http://topic.csdn.net/u/20090405/21/97a137ff-2105-4117-a0c3-39d7f0f1c952.html

Http://topic.csdn.net/u/20090415/13/9ebe5011-c56b-47e6-9f89-40b70896a041.html

However, they are essentially completely different concepts, as shown below:

3-Tier or N-Tier architecture, the middle layer may contain EJB, Enterprise JavaBeans (J2EE), or. NET Enterprise Services, Remoting, and WCF:

Client (WebPage) -- [BLL (business logic layer) -- DAL (data access layer)] (Web Server) -- data source or database

Client (WebPage) -- [BLL (business logic layer) -- DAL (data access layer)] (Web Server + Application Server) -- data source or database

MVC:

◆ Model-includes BLL and DAL. Both View and Controller depend on Model, but Model neither depends on View nor Controller. This is one of the main advantages of separation.

◆ View-only generate output (UI ). For ASP. net mvc, there are no. aspx. cs files such as Code-behind, nor runat = "server" tag, form tag, control declaration, and event processing.

◆ Controller-controls the entire system's workflow, operation logic, error handling, identity authentication and authorization, user input data verification ,... And so on.

In general, Microsoft's ASP. net mvc Framework is to make ASP. NET is more suitable for medium and large projects, and can uniformly plan and control the process of the entire website system (handled by the Controller ), in addition, the division of labor is more effective for development and future maintenance (avoiding repeated custom functions with the same function in many webforms), and controls the overall impact of a function on the system after modification, different functions are clearly cut, so that technical staff with different expertise can perform their jobs separately, which also improves code readability and facilitates testing (TDD, test-driven development) (reduce the amount of Code directly bound to the User Interface) [4], and achieve loosely coupled, making the components easy to replace and reuse. However, ASP. NET programmers must first change their business logic, input verification, and page switching... All other miscellaneous functions are written in the old habits of Code-Behind (aspx. cs.

ASP. net mvc provides a framework that enables you to easily implement the model-view-controller (MVC) pattern for Web applications. this pattern lets you separate applications into loosely coupled, pluggable components for application design, processing logic, and display. ASP. net mvc also greatly facilitates test-driven development (TDD ).

In fact, the invention of MVC Pattern has been around for more than 20 years. Its concept and Framework (MVP) have been around for many years in some frameworks of Java, J2EE, and Struts. The structure of the MVC mode is as follows [4]:

◆ View (JSP) is only used to generate outputs, and does not involve access to data sources, event processing, various logic processing and operations. Therefore, it is more suitable for the division of labor in large projects. This layer is completely produced by the artist (rather than the programmer, artist, and layout ). This layer is like the. aspx front-end page in ASP. NET, that is, the UI (User Interface ).

◆ Model (JavaBean and EJB components) is used to store independent and reusable components, including data source (database) access and commercial logic code, the site preparation and cutting should be completed with the View, so as to retain the system's Elasticity in future expansion or rewriting. This layer is like the custom class, DataSet (. xsd), TableAdapter ,... And so on.

◆ The Controller (Java Servlet) is used to control the "process" of the entire website processing and coordinates the process transfer and redirection between the View and Model, you also need to manage and assign the file to receive the user's "request", that is, it determines which aspx file to display to the user. When a user sends a request from a browser (for example, if you click the control on the page, or enter the data, click submit Button, enter the URL, and click hyperlink... And so on. Some methods defined in the Controller will determine which computing logic to be processed by the Model, and then determine which View to return the processing result to display it.

In addition, the Controller can include error handling, authorization, and input verification... And other functions of the Code, centralized and unified processing, to avoid a large number of repeated code in the traditional WebForm. But to put it bluntly, Controller is actually just a custom class, with some attributes ). Controller is also a lack of ASP. NET.

Figure 1 MVC (Model 2) architecture operation mode, which corresponds to ASP. net mvc project 2

In fact, the website development architecture often referenced by Java, JSP, and JavaEE can also be divided into Model 1 and Model 2. Model 1 can also be divided into two to three types, as shown below:

◆ The first method is to mix HTML and. NET (Java) code, commonly known as the Italian style, such as the early ASP. This kind of Inline code is the most serious problem. It is difficult to maintain the code with low readability.

◆ The second type is to directly access the database by Code-Behind code (. aspx. cs) paired with. aspx, that is, a two-layer architecture. However, this disadvantage is that the Code is difficult to reuse, and because the logic has been written to a fixed page, it will make the system difficult to expand and maintain in the future.

◆ The third type is to access the database or perform business logic operations (JSP + JavaBean) by using custom classes or components in the Custom class library and App_Code folder ). However, this practice still lacks the unified control of flow. As a result, each ASPX (JSP) must verify the user identity, verify request parameters, Process sessions, and perform exception handling, even the coding principles and language sets in the View must be processed in the Code-Behind corresponding to each ASPX. Therefore, it is not suitable for the development, expansion, and maintenance of large systems. Although this architecture can also achieve a virtual three-layer or multi-layer architecture, it is also the limit of ASP. NET.

Model 2, also known as MVC Pattern, is added to the Controller and processes and events are controlled by the center. In addition to making the entire system operational process clearer, it can effectively cut down the work of each layer, and avoid the Code-Behind in the View to process database access and business logic operations in the Model, you do not have to repeat the code "process transfer and redirection" on each page, but the central Controller program code (action method) is used for unified control.

However, the MVC Architecture also has its disadvantages. For example, developers need to take the time to switch concepts and learn a specific Framework, especially. NET developers, because they didn't have the idea of unified Controller coordination process in the past, they had to get used to it again and rewrite a lot of code originally written to different pages in the Controller. In addition, the system must coordinate various classes and objects and exchange data formats and practices in the design phase. Therefore, it is necessary to lengthen the system's prior analysis and planning time. However, if a ready-made Framework like Java Struts or ASP. net mvc Framework can be applied, you can achieve twice the result with half the effort when developing large systems in the future.

ASP. net mvc, must have Visual Studio 2008 + SP1, and download the MVC Suite (after at least two years of research and development, Microsoft finally released the official version April 2009 in 1.0). The download URL is as follows:
ASP. net mvc 1.0 download (2009/04/09 ):
Http://www.microsoft.com/downloads/details.aspx? FamilyID = 53289097-73ce-43bf-b6a6-35e00103cb4b & displaylang = en

After the installation is complete, an "ASP. net mvc Web Application" option will be added when you create a project. After creating a default MVC project, the architecture of the project in VS solution is shown in:

Figure 2 ASPX, ASCX, and MasterPage in the View are purely for display. The Code-Behind file (aspx. cs) is not configured by default)

Such as 2, ASP. net mvc project will automatically generate three folders for storing MVC files, two Controller classes for controlling flows, multiple View pages without Code-Behind, and Global for defining Routing rules. asax. cs.

In fact, when I tried ASP. NET MVC Beta a year ago, the View at that time was still equipped with the Code-Behind file by default, but it was empty and there was only one line of comment:
! -- Please do not delete this file. It is used to ensure that ASP. net mvc is activated by IIS when a user makes a "/" request to the server .--

In the official version released a while ago, the View does not configure the Code-Behind file by default. In addition, ASP. view in. net mvc. In order to make the project development more explicit, there are no page initialization and loading methods, no event handler, and no content except the basic class declaration, the base class is declared as System. web. mvc. viewPage, instead of the System of WebForm in the past. web. UI. page.

The newly created ASP. net mvc project can be executed directly by pressing F5, as shown in 3. However, the MVC View requires the Controller to run before it is displayed (see figure 1. when aspx is set to the start page and F5 is pressed, HTTP 404 occurs. the resource cannot be found. "error, that is, if you want to directly navigate to this page, it will not work.

Figure 3 ASP. net mvc project Homepage

You will find that the URL in the browser will be like the following, the URL is not a specific. aspx extension:

Http: // localhost:Port/Home/index

Http: // localhost:Port Number

In fact, the content of this page is displayed by capturing the content of Index. aspx under the Views/Home folder. It is configured by Global. asax. cs and uses "URL Routing" to allow users to access the website [14] according to your own rules.

There are two hyperlinks on the right of the homepage in Figure 3, which can be directed to "LogOn. aspx "," About. aspx page. However, the page to which hyperlink directs is not written to the View page (no Code-Behind is available), but is unified by Global. asax. cs defines the Routing rules to parse which Controller custom class should be thrown to the browser when it receives the URL, form or any request; then the specified Controller (for example, HomeController automatically generated in 2 by default. cs), which defines one or more systems. web. mvc. actionResult class, and View method (called action method) to set the View (PAGE) to which the UI render is returned, that is, as mentioned at the beginning of this article (refer to figure 1 in this post), Model 2 The Controller file is used to uniformly control the process and page orientation of the entire ASP. NET system, rather than writing it to various aspx. cs files.

The following code is part of Global. asax. cs. You can refer to the structure of Controller and View in section 2 to read the code:

Using System. Web. Mvc;
Using System. Web. Routing;

Public class MvcApplication: System. Web. HttpApplication
{
Public static void RegisterRoutes (RouteCollection routes)
{
Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");

// C #3.0 "Anonymous Type" Syntax
Routes. MapRoute (
"Default", // Route name
"{Controller}/{action}/{id}", // URL with parameters (controller name/operation name/ID parameter)
New {controller = "Home", action = "Index", id = ""} // Parameter defaults
);
}
}

The three parameters in the MapRoute method are routes, route name, and URL. The first parameter "Default" indicates the Default. aspx in the project (not in the View folder ). This URL Routing is used to solve the problem that the user cannot find the file when accessing the domain name directly. Therefore, use this method to change the Home page to Routing to Home/Index. Therefore, when you enter:

Http: // localhost: Port Number/Default. aspx

Or

Http: // localhost: Port Number

It will also be directed to Views/Home/Index. aspx in Figure 2.

System. Web. Mvc Namespace (MSDN Library, no Chinese version ):

Http://msdn.microsoft.com/en-us/library/system. web. mvc. aspx

RouteCollectionExtensions. MapRoute Method:

Http://msdn.microsoft.com/en-us/library/dd470521.aspx

ASP. net mvc Framework (Part 1) (ScottGu's blog published on April 9, November 2007, in the figure showing ASP. net mvc in Beta ):

Http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx

On the homepage of Figure 3, when you move the cursor to the hyperlink on the right, the name of the page (. aspx) is not directly displayed in the browser's address bar and the Information bar below the browser, because the request "redirection" operations are all handled by the Controller, that is, by HomeController in Figure 2. in cs, the configured System. web. mvc. the actionName of the ActionResult class is specified, so the website of the browser is still maintained. the Html in the Master (MasterPage. the configured actionName (the second parameter "Index" and "About" of the following two lines of code) is bound by ActionLink instead of ASP.. NET 1.x/2.0, which is directly displayed in the address bar. the name of the aspx page.

Part of the Code for Site. master is as follows:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>

    <ul id="menu">
    <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
    <li><%= Html.ActionLink("About", "About", "Home")%></li>
    </ul>

In addition to controlling the entire website process, the Controller can also avoid a large number of code duplication, that is, to uniformly process some functions that can be "shared" by the system. For example: verify the user identity, input verification (validate), Session management, or when an item in the shopping cart is added, modified, or removed on a shopping website, all users share the same "shared series" processing; and when you want to check out, you can calculate the number of shopping items and the unit price, or add a Collection Data Structure object that stores the shopping details to the Session, and then switch to a page (View ).

Summary:

This post is only for. NET technical personnel. It serves as an introductory article to get a preliminary understanding of MVC Pattern and ASP. net mvc Framework. If you are interested in in-depth research, you can refer to the "related documents" at the bottom of this post. There are many related posts in the blog Park and on the Internet. For general MVC concepts, refer to the network theory, related books of JSP/Struts/J2EE, or Compound Pattern in Design Patterns) "[15].

As mentioned in MSDN Magazine [7], ASP. net mvc is not used to replace traditional ASP. NET WebForm, the two have their own advantages and disadvantages, and the future ASP. net mvc may also be continuously improved on the UI, control drag, and Routing. However, as a technician, it is best to clarify the characteristics and advantages and disadvantages of the two [4] [6] earlier to assess whether deep learning is required or to import projects in the future; it takes at least two years for Microsoft to develop this framework with great care.

  1. Analysis of TempData mechanism in ASP. NET MVC
  2. Technical expert comments ASP. net mvc 1.0
  3. ASP. Net MVC Framework configuration and Analysis

Related Article

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.