MVC's advantage over WebForm, why use MVC

Source: Internet
Author: User
Tags http post

Objective

If you look at the recent Microsoft agenda, you will find that their focus now is on MVC, but MVC. The question is why Microsoft is so keen to discard traditional aps.net webform and turn to ASP. This article is mainly to discuss this issue.

ASP (behind code)--Gospel and curse Webform

If you are closely following the ASP. NET WebForm technology, you will find it closer to the visual design, in other words, developers only need to drag the control from the design panel to complete the UI, and then in behind code to implement the logical code to complete the final Web page functionality.

So in other words, when you drag a button from the design panel, you'll generate an object in the background code that will simply implement the event response code in the button's Click event.

public partial class WebForm1:System.Web.UI.Page    {        protected void Page_Load (object sender, EventArgs e)        { c3/>//Developers write code here        }        protected void Button1_Click (object sender, EventArgs e)        {            // Developers write code here        }    }

When we drag some UI elements in the page, double-click them to generate a series of event response codes in the background code, all in the ASPX.CS file.

This background code file is the key to ASP. WebForm, which you can apply in this file. NET features, including events, delegates, HTTP protocols, sessions, and so on.

But there are 5 problems with this behind code pattern, and we'll talk about these 5 questions each, and use MVC's design ideas to solve these problems separately.

Issue 1: View-based scenarios to address behavior-based requirements

Our site is ultimately used by users, users visit the site will certainly have a specific purpose, the site to do is by allowing users to interact with the behavior to achieve their intended purpose. For example, when a user visits a shopping site, perhaps his interaction will be like this:

    • Buy Products
    • Print Invoice

These interactions are implemented through button clicks, right-click, and Browser URLs. Since these interactions are based on the HTTP protocol, if we can map these interactions to specific methods, the entire architecture will be much simpler.

But Microsoft can't do this because it wants to implement Visual Web page programming, so they finally choose a view-based solution.

As you can see, the entire request process looks strange:

    • The user initiates an HTTP request, such as an HTTP Post/get
    • The IIS server maps the request to the view
    • The view invokes the life cycle of the page and, through event-driven, invokes the appropriate interaction method
    • Finally show the result of the interaction to the end user

Since Microsoft chose a view-based design from the outset, it is difficult for the architecture itself to move closer to design ideas based on user interaction. In other words, when a user makes a "buy" request, it first accesses the view page "Shopping.aspx", the background logic code in "Shopping.aspx.cs", the page life cycle will return the results of the page to the user.

If the idea of using MVC is based on user interaction, then the request flow will be as follows:

Issue 2: Side effects of bad architecture-tight coupling

When you choose a wrong architecture, there will be a lot of hard-to-resolve side effects in the future, and this is the problem in ASP. WebForm. Although the behind code daemon is separated into different files, the ASPX.CS file and the aspx file are tightly linked, which results in a high degree of coupling between the system and is difficult to decouple and is a headache.

Simply put, it's hard to simply peel off Customer.aspx.cs and customerdetailed.aspx, and the backend code is tightly tied together and hard to reuse. If we can get the request through action first, and the data from the different view view,action is determined by the controller which view to display, then the request process will be this:

So we can easily control whether the end result is a mobile page display or a normal page display, the following code:

Public ActionResult Index (string devicetype) {           if (ViewType = = "Mobile")            {                return View ("Mobileview");            }            Else            {                return View ("Normalview");}            }
Problem 3:html is not the only return type

The default return type is fixed, and all are HTML types, because the view and background code behind codes are tightly coupled. If you want to change the type, you must set Content-type and call the Response.End method.

If we create an action, the returned type is specified by the action and the system can output different return types in the same action depending on the conditions. The code is as follows:

Public ActionResult Index (string viewtype) {            if (ViewType = = "json")            {                return json (New Customer (), jsonrequestbehavior.allowget);            }            else            {                return View ("Displaycustomer", New Customer ());}            }
Issue 4: Flexible combination of views and data

WebForm is a view-first schema, so the view determines the data that is presented, so the view is very extensible, and if you encounter a complex data structure, this approach becomes inadequate.

But if it is a behavior-first architecture, when we trigger an action, the action can select different data models and view structures based on different requests, such as:

In MVC, you can select the same data model in different views, such as the following code, where the CustomerData data can be bound either in the Detailcustomer view or in the customer view.

Public ActionResult Index (string Viewname,customer customerdata) {            if (ViewName = = "detailed")            {return View (" Detailcustomer ", customerdata);            }            else            {                return View ("Customer", CustomerData);}            }

This is very cumbersome to implement in WebForm.

Question 5, behind code as a normal class for unit testing

Behind code daemon is a very large class in WebForm and cannot be instantiated easily. To know that WebForm is inherited from the page class, the page class cannot be instantiated directly because it has too many dependencies.

public partial class WebForm1:System.Web.UI.Page    {        protected void Page_Load (object sender, EventArgs e)        { c3/>} public        void Button1_Click (object sender, EventArgs e)        {            session["somesession"] = "was this set";        }    }

Why do you want to instantiate the page class? One of the reasons is that unit tests can be facilitated. For example, I want to test a button click event to check if the session is set successfully. The code in WebForm doesn't look so comfortable:

[testmethod]public void TestMethod1 () {            Webapplication22.webform1 obj = new Webapplication22.webform1 ();            Obj. Button1_Click (this, new EventArgs ());}

And also throws an exception at run time:

In MVC, this class becomes a normal class, we can instantiate it in the test project, and unit test the attribute method, Session, ViewBag, TempData, etc. in the class.

public class Homecontroller:controller//ß This class was simple {public        actionresult Index ()        {            session["somesession"] = "are this set";            Return View ("Someview");}        }
So do you choose an MVC solution?

To switch from the WebForm architecture to the MVC architecture, here are a few things you need to do:

    • Transfer the code in behind to the Controller class and convert the original method to the action method.
    • The middle tier is replaced with a data model and a logical interface.
    • View views are used only to show data and page layouts.
    • There is no change in the DAL layer and other layers because it has little to do with behind code.

So in the MVC architecture, the user's request is divided into the following 3 steps:

    • When an end user sends a request, the router routes the request to the appropriate controller,controller, which is a collection of logical entities and action actions.
    • The controller maps the request to a specific action.
    • The action has two tasks, the first is to get the right data, and the second is to bind the data and view views together. The action creates the data model and connects the data model to the specified view, outputting the final corresponding result.

Link: http://www.codeceo.com/article/webforms-vs-mvc.html
English Original: Webforms vs MVC and why MVC is better?
Translation Code Agricultural Network-Xiao Feng
[ reproduced in the text must be marked and retained in the original link, translation links and translators and other information. ]

MVC's advantage over WebForm, why use MVC

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.