The basic principle and realization principle of MVC model

Source: Internet
Author: User

Application and implementation of "reprint" MVC Architecture in ASP.

Absrtact: This article mainly discusses the principle, advantages and disadvantages of MVC architecture, and the benefits that MVC can bring to Web applications. Taking "Chengdu Information Assets management System" as an example, this paper introduces the concrete implementation of the project in ASP. Designed to help web design developers better understand and master MVC and use MVC to build good Web applications.

Keywords: MVC, views, controllers, models, ASP.

Application and implementation of MVC construction in ASP.

Abstract:this article mainly elaborated the construction principle of MVC, the merits and shortcoming as well as MVC can Be an advantage, which the WEB application brings. And take ' The Chengdu Informationization Property Management System Management system ' the frame design as the example, in Troduces its concrete realization in detail under ASP. NET environment. Purpose of helping Web to design a exploiter better understanding and to grasp MVC, reasonably constructs the Outstanding Web application using MVC.

KEYWORDS:MVC, View, Controller, Model, ASP.

0 Introduction

Many Web applications retrieve data from the data store and display it to the user. After the user changes the data, the system then stores the updated content in the data store. Because the critical flow of information occurs between the data store and the user interface, many applications tie together the two parts of the data and user interface to reduce the amount of coding and improve application performance. However, this seemingly natural approach has some big problems. One is that changes to the user interface tend to be much more frequent than changes to the data storage system. The second is that this coupling tends to be and other business logic. So how do you modularize the user interface functionality of your WEB application so that you can easily modify individual parts individually? The object-oriented design pattern is a summary of experience, and the MVC architecture is a good solution to the above problems.

. NET is the mainstream platform for designing and developing various Web applications today, and the MVC architecture has a mature design scheme on the Java EE platform. NET platform, but it is seldom used. So it is still very meaningful to discuss its application and implementation in ASP.

This paper first discusses the principles, advantages and disadvantages of the MVC architecture and the benefits it can bring to the Web application. and combined with the author in the "Chengdu Microsoft Technology Center" internship, Research and development project experience. This paper introduces a kind of implementation method in ASP. Designed to help web design developers better understand and master MVC and use MVC to build good Web applications. Although this article is implemented in a. NET environment, this does not prevent you from understanding the MVC architecture. Learning the MVC architecture is about learning its ideas.

1 MVC Introduction

MVC is a software development architecture that contains a number of design patterns [1], most closely three: OBSERVER (Observer mode), Composite (combination mode), and strategy (policy mode). [2] MVC was originally used to build the user interface in Smalltalk-80.

The MVC architecture separates data processing, program input and output control, and data display, and describes the communication between objects of different parts. Makes software maintainability, extensibility, flexibility and encapsulation greatly improved; MVC (Model-view-controller) decomposes the composition of the system into three parts of M (model), V (view), C (Controller). The view represents the display of data on the screen. The controller provides process control, which acts as a connection between the model and the view. The controller itself does not output any information and does any processing, it is only responsible for the user's request to the model of the operation, and call the corresponding view to display the model processed data. The relationship between the three is like 2.1:

Figure 2.1 MVC Diagram

2. Why use the MVC architecture in Web applications

Changes in user interface logic are often more frequent than business logic, especially in Web-based applications. For example, you might add a new user interface page, or you might completely disrupt an existing page layout. Do not affect the data and business logic as much as possible for the changes that are displayed.

Most Web applications now mix data codes with representations. The more experienced developers separate the data from the presentation layer, but this is often not easy to do and requires careful planning and ongoing attempts. MVC is fundamentally mandatory to separate them. While it takes some extra work to construct an MVC application, the benefits are no doubt.

2.1 Increase code Reuse rate

The most important point is that multiple views can share a model, whether the user wants a flash interface or a WAP interface, and can handle them with a single model. Because data and business rules are separated from the presentation tier, you can maximize the reuse of code.

2.2 Improve the maintainability of the program

[3] Because the model is self-contained and detached from the controller and view, it is easy to change the data layer and business rules. For example, porting a database from MySQL to Oracle, or changing an RDBMS-based data source to LDAP, simply changes the model. Once the model is implemented correctly, the view will display them correctly, regardless of where the data comes from. The application of MVC architecture makes the three parts of the program oppose each other, which greatly improves the maintainability of the program.

2.3 Facilitates team development

In the development process, can better division of labor, better collaboration. Helps develop high-quality software. A good project architecture design will reduce coding effort: the MVC Architecture + code generator is the ideal choice for most Web applications. Part of the model, and stored procedures are generally available tools are automatically generated. Control (Controller) is relatively stable, generally due to architects (and possibly experienced people) to complete, then the entire project needs to manually write code where there is only the view. In this mode, personal ability is not particularly important, as long as the people who understand the basis of grammar can be written, regardless of the project members to write what kind of code, is within the control of the project manager. Even if there is a substitution in the middle of the project, it won't be too much. In the development of a team with uneven individual ability, it is very ideal to use MVC development.

The principle and implementation of 3 MVC in ASP

ASP. NET provides a similar environment for implementing this pattern well. Implement a view by developing a user part in an ASPX page or inheriting a master page masterpage, the function of a controller can generally be implemented in the corresponding logical function code (. cs), and the model usually corresponds to the business part of the application system. Models typically contain business logic, business rules, and data access layers. MVC can be used in conjunction with classic n-tier structures. The user display (view) is separated from the action (Controller), which improves the reusability of the code. Separating the data (model) from the Action (Controller) of its operation can design a system that is independent of the data stored in the background. As far as the nature of MVC structure is concerned, it is a method to solve the problem of coupling system [4]. Implementing an MVC-based application requires completing the following steps, as shown in Figure 3.1 on the right:

1, analysis of the current application, decomposition system functions:

Analyze the current application problem, isolate the system's kernel function (Model), the system's input and output (View), the system's transmission flow control, behavior control and other control functions (Controller) three parts.

2. Design and Implementation model:

Design the model part to encapsulate the application functionality, attributes. Provides access to the display data, provides operations to control internal behavior, and other necessary operating interfaces. The composition of this part is closely related to the specific application problem.

3. Design and Implementation view:

Design the display of each view, which takes the data from the model and displays the data on the screen. Provides a send user request to the controller, which allows the controller to select a view.

4, design and implementation of the Controller:

For each view, the implementation of the user's request is mapped to the model. And according to the model processing results, select the appropriate view display. Under the influence of the model State, the controller uses a specific method to accept and interpret these events. The initialization of the Controller establishes a connection to the model and the view (which is typically used in observer mode) and initiates the event-handling mechanism. The concrete implementation of the event-handling mechanism relies on the working platform of the interface.

MVC does not have a clear definition, it represents only a software design idea. Therefore, in different application environments, there may be different ways of implementation. Only a deep understanding of its thinking, the actual situation. To build a reasonable application. The following is an example of the framework design of "Chengdu Informatization Asset Management System", and introduces an implementation method of MVC framework under ASP. The framework does not use observer mode because of dependencies (there are only two views in this project, List page and edit, view details page. and the possibility of adding views in the future is not likely to be fixed or almost fixed, adding an observer pattern only increases system complexity.

The framework structure of this project includes logical structure Figure 3.2 and physical structure Figure 3.3 two parts.


From the logical structure diagram, you can see that access to the database is not fully using stored procedures, which is due to operational efficiency and development efficiency considerations.

The stored procedure here includes only the basic CRUD four operations for each entity.

3.1 View (view)

3.1.1 Principle

Views are used to manage the display of information, which provides a user interface. With multiple user parts that contain a single-page display, a complex web page can present content from multiple data sources, and Web page people, artists, can participate in the development and maintenance of these web pages on their own. Under ASP. NET, the implementation of the view is simple. Page development can be done directly in the integrated development environment by dragging parts just like the Windows interface. Each page can also be in the form of a composite view: A page consists of multiple sub-views (user parts), or you can inherit the master page masterpage. A child view can be a Web custom part or Web page that is nested within the simplest HTML part, a server part, or multiple parts. The page is defined by the template, which defines the layout of the page, the label and number of the user part, the user specifies a template (where the template refers to an HTML page, an ASP. NET page, a user part, and so on), which automatically creates the page based on that information. For static template content, such as site navigation on the page, menus, links, these use the default template content configuration, for dynamic template content (mainly business content), because the user's request is different, can only use late binding, and for the user's different, the user part of the display content filtering. It enhances reusability and simplifies the layout of your site by using a combination of pages that are composed of user parts based on template configuration. In. asp.net2.0, you can use MasterPage to simplify the view design. The skin (skins) set in MasterPage will be based on the them (theme) in the different sub-views (inherited from the MasterPage page). Automatically selects the appropriate skin display. It can be said that MasterPage is a very good embodiment of the idea of MVC architecture.

The general process of the View section is as follows: first, the page template defines the layout of the page, the page profile defines the specific contents of the view label (the user part), and the page layout policy class initializes and loads the pages, each user part initializes according to its own configuration, loads the validator and sets the parameters, As well as the delegate of the event; After the user submits, through the validation of the presentation layer, the user part automatically submits the data to the business entity as the model.

This part mainly defines the Web page base class pagebase, the page layout policy class pagelayout, completes the page layout, is used to load the user part to the page, the user part base class Usercontrolbase namely the user control framework, is used to dynamically load the inspection part, and personalization of user parts. To achieve the flexibility of Web applications, the View section also uses a number of configuration files such as template configuration, page configuration, path configuration, authentication configuration, and so on.

3.1.2 Implementation

A good interface architecture design will reduce the interface adjustment time. Under. NET should take full advantage of asp.net2.0 new features, automatic navigation, SITEMAP, MasterPage, membership, MultiView, them, skin and so on. In this project, the view of each module is actually only two, one is to display a list of multiple data pages, one is to edit, and view the details of the page. Because the view type is almost fixed, you do not need to add observer (Observer) mode. Make all the edit pages inherit from the master page dialog.master, and all list pages inherit the "master Page main.master". 3.4

The dynamic display area for each list page is only a contentplaceholder, or yellow area section, which guarantees the same type of page style. In accordance with the naming conventions and easy to understand principles, we have all the edit page suffix named "editpg.aspx", all the list page suffix is named "listpg.aspx". Changes to the view can be achieved through the asp.net2.0 theme (Themes). In this example, the same view is used to edit and view the details page. If you want to add a different view, simply add the corresponding master, and complete the specific display requirements. In this project, all editing pages generally require only the following methods provided by the base class (Dialoguibase).

Get the data and store it in the corresponding model for view use

protected override void Getdatafromdb (object keyValue){...}

Populate the edit or display interface with data from model

protected override void Setedittext (){...}

Re-fill in the part content of the edit box page and do not assign a default value to part content that may be repeated by some users

protected override void Resetedittext (){...}

Check user input Correctness

protected override string Checkuserinput (){...}

Save user input, update user input to database

protected override Object Saveedittext (object KeyValue){...}

All list view is generally used only for the following virtual methods provided by the implementation base class (Gridviewuibase).

Returns the GridView that is used in the subclass, which must inherit

protected override GridView Getgridview (){...}

Returns the name of the check box in the GridView check box column template in the child class, and the subclass chooses to inherit from the template column

protected override string Getgridcheckboxname (){...}

    typically no handling of inherited methods

   //binding a DataGrid part event,

     protected override void bindgridevent ()

   //binding except through Getdatagrid () Client-side events for parts other than the incoming DataGrid assembly

     protected override void  Bindcontrolevent ()

   //  Returns the data source used by Gridviewlist,  subclasses must inherit

     protected override object getdatasource ()

  //  multiple records deleted, In the Delete button event, call

    protected override void delrecords (object  keyvaluesstring)

   //  return hashtable
with CommandName as key to Grideventpageparam type parameter as content
Protected override hashtable getdialogparams () {...}

From the above code can be easily found, whether it is a list page or edit the page, there is no process-related things, this is what MVC is to do, the view contains only the data display, the process is completely controlled by the base class. The benefits are obvious. The view that different people write out also has the same style.

3.2 Controller (controllers)

3.2.1 Principle

Controller controllers are a bridge between model and view that can dispatch a user's request and select the appropriate view for display, as well as interpreting the user's input and mapping them to the actions that the model layer can perform. Each aspx in. NET corresponds to a back-end code aspx.cs, which enables the controller to function conveniently through aspx.cs. Each ASP. NET page has a mechanism to implement the method that the part in the page wants to invoke in a class that is detached from it. These aspx and ascx file backend code inherits the System.Ul.Web.Page class execution controller functionality, which includes various initialization and control functions. The Page_ Load event is called when an ASPX page is loaded, and the Page_Unload event is called when the ASPX page is unloaded from memory. The control event event is invoked if a part triggers the page to be reloaded.

3.2.2 Implementation

The control class for all editing pages is DialogUIBase.cs, which completes the Process control and request control of all editing pages, and the control class for all list pages is GridViewUIBase.cs, which completes the Process control and request control of all list pages. The two classes are located under the App_Code folder.

The edit page base class (Dialoguibase) and the list page base class (Gridviewuibase) all inherit from System.Web.UI.Page, both contain two parts, one is the virtual method for the view subclass inheritance, and the other is the method to control the view sub-class process.

The main methods in Gridviewuibase in this example are:

Methods for inheriting from subclasses#region methods for inheriting from subclasses

Returns the GridView used in subclasses

Protected virtual GridView Getgridview (){...}

Returns the name of the check box in the GridView check box column template in the child class, and the subclass chooses to inherit from the template column

Protected virtual string Getgridcheckboxname (){...}

Returns the data source used by the GridView

Protected virtual Object Getdatasource (){...}

Delete the selected data from the view

protected virtual void Delrecords (object keyvaluesstring){...}

Returns a hashtable that takes commandname as key to grideventpageparam the type parameter as content

Protected virtual hashtable getdialogparams () {...}

Binds the GridView part client event to the client event that binds the default binding function, all rows of the bound column call the same dialog page, and the function needs to be overridden if a different row is to be called on a different dialog page

protected virtual void bindgridevent (){...}

Binds the client click event to a part other than the GridView part passed through Getgridview ()

protected virtual void bindcontrolevent (){...}

Button Event Bindings

public void bindbtnevent (...) {...}

Table Event Bindings

public void bindgridevent (...) {...}

Dialoguibas class and Gridviewuibase class, the design ideas are exactly the same. So no more examples. From the above can be found in the gridviewuibase, the realization of the control of the view. Depending on the user's request, different model is called for processing.

3.3 Model (models)

3.3.1 Principle

The model object represents business rules and business data, and a single model represents an object in the problem domain, or an entity. So the model should encapsulate the application function and application attribute of the system. Provides access to the display data, provides operations to control internal behavior, and other necessary operating interfaces. The composition of the model is closely related to the specific application problem. Typically models include data access, business logic, and business rules. In ASP. NET, a simple model can be easily implemented with automatic code generation tools. VS IDE 2003, VS IDE 2005 itself provides good support for easily generating strongly typed datasets and DataTable from data sources such as databases or XML. The data access layer can use Application Block blocks. or Enterprise Library and other open source components. Of course you can also do these tasks manually, if you wish.

3.3.2 Implementation

In this example, both the business processing object and the business entity object inherit from the EntityBase class. The EntityBase class is also inherited from the entity class. The entity class is the base class for database access. It primarily contains methods that are inherited by subclasses (CRUD operations that use stored procedures to complete the database). and methods that are called by the external class (model completes the crud operation). There are two ways to set it up because of the need for a logical structure.

The main methods for inheriting subclasses are as follows:

protected virtual void Init (){...} Perform the necessary initialization

Protected virtual bool Proc_insert (){...} Add to

Protected virtual bool Proc_update (object KeyValue){...} Update

Protected virtual bool Proc_readbykeyvalue (object KeyValue){...} Retrieval

Protected virtual bool Proc_delete (object KeyValue){...} Delete

Protected virtual DataTable Proc_readall (){...} Retrieve all

protected virtual void afterload (){...} Before the data in the database update model

protected virtual void BeforeSave (){...} Before updating a database with a model

The main methods for external invocation are as follows:

Public DataTable ReadAll (){...}  //retrieves all

Public object insert () {...}  //Add

Public object update (object keyvalue) {...}  //Update

Public bool load (object keyvalue) {...}  //Fill Model

Public bool delelte (object keyvalue) {...}  //Delete

Public void clear ()  //clear model

The EntityBase class simply implements the four virtual crud methods of the base class (Entity), and defines the properties associated with the model itself. Since model inherits from the EntityBase class, if a model requires additional action, it can be added to the afterload () or BeforeSave () method corresponding to the model.

Extended design of 3.4 MVC architecture

By using the MVC pattern in ASP. NET, you can build a Web application that has good extensibility. The MVC architecture can easily implement the following features:

① implement multiple views of a model;

② adopts multiple controllers;

③ when the model changes, all views are automatically refreshed;

④ all the controllers will work independently of each other.

This is the benefit of the MVC pattern, and it's easy to add a lot of program functionality by simply modifying or adding new classes on previous programs. Many of the previously developed classes can be reused, and the program structure simply no longer needs to be changed, the various types of mutual independence, easy to group development, improve development efficiency. The following is a discussion of how to implement a model, two views, and a controller program. The model classes and view classes do not need to change at all, as is the case with the previous one, which is the benefit of object-oriented programming. For a class in a controller, you only need to add another view and associate with the model. 3.5 of views, controllers, and models are shown in this mode.


Other forms of MVC can also be implemented such as: a model, two views, and two controllers. As can be seen from the above, applications implemented through the MVC pattern are extremely well-extensible and are the future direction of the net object-oriented programming.

4 Advantages and disadvantages of the MVC Architecture 4.1 MVC Benefits

The benefits of MVC are reflected in the following areas:

(1) Facilitate the team to develop division of labor and Cooperation and quality control, reduce development costs.

(2) Multiple views can be established and used at run time for a model. The change-propagation mechanism ensures that all related views are in time to get model data changes, so that all associated views and controllers behave in a synchronous manner.

(3) The view and controller pluggable, allowing the exchange of views and controller objects, and can be dynamically opened or closed according to demand, and even during the operation of object substitution.

(4) Portability of the model. Because the model is independent of the view, it is possible to migrate a model independently to the new platform work. All you need to do is make new changes to the view and controller on the new platform.

(5) A potential frame structure. The application framework can be built on this model, not just in the design of the interface.

Disadvantages of 4.2 MVC

The shortcomings of MVC are reflected in the following areas:

(1) Increase the complexity of the system structure and implementation. For a simple interface, strict adherence to MVC, which separates the model, view, and controller, increases the complexity of the structure and may result in excessive update operations and reduced operational efficiency.

(2) The view is inefficient in accessing model data. The view may need to call model multiple times to get enough display data.

(3) It's not easy to fully understand MVC. Using MVC requires careful planning, and because its internal principles are complex, it takes some time to think. At the same time, due to the strict separation of the model and view, it is also difficult to debug the application.

Conclusion

Compared with the intrinsic model of the software, the user interface needs to change frequently, and the MVC design pattern can satisfy the requirements of the interface, and make the software's computational model independent of the interface composition. You can also build a large distributed application framework based on this model.

MVC is not a good fit for small or medium-sized applications, and spending a lot of time applying MVC to applications that are not large in size will often outweigh the costs.

MVC is a software development architecture. As with other design patterns, it is neither omnipotent nor immutable. Should be used flexibly according to the specific situation. In the example project above, in order to improve the efficiency of running and development. There are two ways of accessing the model design.

The MVC in the example uses a centralized control approach. A list controller gridviewuibase, which corresponds to multiple list views. An edit controller dialoguibase the edit, view Details view. For each model, there are only two views and are almost fixed. So there is no increase in observer (Observer) mode. This reduces the complexity of the system. The most exciting part of this example is the design of the controller. Each view execution process is completely encapsulated in the controller. Because the view does not contain any control information, the process information. So the view coder does not have to understand the stateless features of HTTP and so on. For them, development WebForm and WinForm are the same. Of course, this design also has its shortcomings, if you modify the display of a view, it is possible to modify the relevant controller.

Reference documents

[1] (US) Alan shallowly & James R.trott. Design pattern Fine solution. [M]. BEIJING, Tsinghua University Press, 2004,p:166-177,p:51-61

[2] Su Xiaoming. Design and implementation of production model structure of petrochemical enterprise based on MVC model. [Master's thesis]. Dalian University of Technology, Dalian, 20050618

[3] Cai Yang. Research and implementation of collaborative design system based on MVC design pattern. [Master's thesis]. Chengdu, Southwest Jiaotong University, 20050601

[4] Lin Chang is required. Research and application of multi-client MVC design pattern. [Master's thesis]. Lanzhou, Lanzhou University of Technology, 20050501

The basic principle and realization principle of MVC model

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.