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, but technicians who are willing to accept new ideas will usually live for a long time 」. This post only introduces the concept and architecture of MVC pattern. It is for those who have never touched the MVC framework. net technical personnel as a reference to assess whether to study in depth or import projects in the future.
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 the model neither depends on view nor controller. This is one of the main advantages of separation
● View -only generates output (UI ). Use ASP. net MVC, There is no code-behind. aspx. the CS file does not contain the 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, in addition, different functions are clearly cut, so that technical personnel with different expertise can perform their respective duties, which also improves by the way.Code(TDD, test-driven development) (reduce the amount of Code directly bound to the User Interface) [4], and achieve "loosely coupled )」, make the components easy to replace and reuse. However, ASP. NETProgramYou must first change the 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, MVC pattern has been invented for more than 20 years, and its concept and framework (MVP) have long been used 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 logical 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) are used to store independent and reusable components, including access to data sources (databases) and Code of business logic. They should be completely cut with the view, in order to retain the system's Elasticity in future expansion or rewriting. This layer is like the custom class, dataset (. XSD), tableadapter ,... And so on.
●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) through a custom class library or a custom class or component in the 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, in the design phase, the system must first coordinate various classes and objects and exchange data formats and practices between them. 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 structure 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 Number/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), the architecture of 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. actionlink binding, the configured actionname (that is, the second parameter "Index" and "about" of the following two lines of code), 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 user identity, input verification (validate), session management, or when an item in a shopping cart is added, modified, or removed from a shopping website, all users share the same "common logic" processing, and 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, as a preliminary introduction to MVC pattern and ASP. net mvc FrameworkArticle. 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, you can also refer to JSP/struts/J2EE Network forums, related books, or compound pattern in design patterns) "[15].
As mentioned in [7] In msdn magazine,ASP. net mvc is not used to replace the traditional ASP. NET webform. Both of them have their own advantages and disadvantages.In the future, ASP. net mvc may continue to improve 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 to study in depth or import projects in the future; it takes at least two years for Microsoft to develop this framework with great care.
--------------------------------------------------------
Related Files:
[1] MVC: the official Microsoft ASP. NET site:
Http://www.asp.net/mvc/
Http://www.asp.net/learn/mvc/
Http://www.asp.net/learn/mvc/tutorial-01-cs.aspx
Http://www.asp.net/learn/mvc/tutorial-02-cs.aspx
Http://www.asp.net/learn/mvc/tutorial-03-cs.aspx
...
Http://www.asp.net/learn/mvc/tutorial-38-cs.aspx
Http://www.asp.net/learn/mvc-videos/
Http://forums.asp.net/1146.aspx
[2] ASP. NET-home:
Http://aspnet.codeplex.com/Wiki/View.aspx? Title = MVC
[3] scottgu's blog (general manager of Microsoft development ):
Http://weblogs.asp.net/scottgu/archive/tags/MVC/default.aspx
[4] Model-View-controller (msdn ):
Http://msdn.microsoft.com/en-us/library/ms978748.aspx)
Http://msdn.microsoft.com/zh-cn/library/ms978748.aspx)
[5] Page controller (msdn ):
Http://msdn.microsoft.com/en-us/library/ms978764.aspx
Http://msdn.microsoft.com/zh-cn/library/ms978764.aspx
[6] Implementing Model-View-controller in ASP. NET (msdn ):
Http://msdn.microsoft.com/en-us/library/ms998540.aspx
Http://msdn.microsoft.com/zh-cn/library/ms998540.aspx
[7] Building Web apps without web forms (msdn magazine ):
Http://msdn.microsoft.com/en-us/magazine/cc337884.aspx
Http://msdn.microsoft.com/zh-cn/magazine/cc337884.aspx
[8] Learning ASP. net mvc 1.0 (I) from scratch (zi Qiu's blog ):
Http://www.cnblogs.com/zhangziqiu/archive/2009/02/27/ASPNET-MVC-1.html
[9] Terry Lee ):
Http://www.cnblogs.com/Terrylee/archive/2008/01/01/aspnet-mvc-framework-vs-wcsf-mvp.html
ASP. net mvc Framework experience (1): start with a simple instance (terrylee ):
Http://www.cnblogs.com/Terrylee/archive/2007/12/11/aspnet-mvc-framework-overview.html
[10] blog Park ASP. net mvc technical topics:
Http://kb.cnblogs.com/zt/mvc/
[11] Step by Step learning ASP. net mvc 1.0 to create the nerddinner sample program:
Http://blog.entlib.com/entlibforum/archive/2009/03/28/asp.net-mvc-1.0nerddinner-part-1.aspx
[12] ASP. net mvc development experience sharing (1): Development Process (Traditional Chinese ):
Http://blog.miniasp.com/post/2009/01/ASPNET-MVC-Developer-Note-Part-1.aspx
ASP. net mvc development experience sharing (2): dancing with the original code (Traditional Chinese ):
Http://blog.miniasp.com/post/2009/02/ASPNET-MVC-Developer-Note-Part-2.aspx
Study the oxite CMS system! (Traditional Chinese ):
Http://blog.miniasp.com/post/2008/12/Microsoft-Open-Source-content-management-system-Oxite-using-ASPNET-MVC.aspx
[13]. NET Framework Class Library:
System. Web. MVC namespace (no Chinese version ):
Http://msdn.microsoft.com/en-us/library/system.web.mvc.aspx
[14] URL routing:
Http://blog.csdn.net/chsword/archive/2008/03/11/2165866.aspx
Http://www.cnblogs.com/terrylee/archive/2007/12/16/aspnet-mvc-framework-url-routing.html
Http://www.cnblogs.com/qleelulu/archive/2008/03/17/1109893.html
--------------------------------------------------------
Related books:
[15] Head first design model, Chapter 12:
Http://www.dearbook.com.cn/book/213719
Http://www.china-pub.com/36020
[16] Free ASP. net mvc ebook Tutorial:
Http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx
[17] ASP. net mvc in action:
Http://www.manning.com/palermo/
[18] Pro ASP. net mvc framework:
Http://www.apress.com/book/view/1430210079
[19] professional ASP. net mvc 1.0:
Http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-MVC-1-0.productCd-0470384611.html
--------------------------------------------------------