Click here to Skip to main content
14,271,765 members

Webforms vs MVC and Why MVC is better ?.

Rate this:
4.90 (90 votes)
Please Sign up or sign in to vote.
4.90 (90 votes)
27 Sep 2014CPOL
In this article we have explained why MVC and we will be comparing MVC with webforms.




ASP.NET Webform behind code –boon and curse

Problem 1 :- View based solution for Action based requirement

Problem 2:- Side effects of bad architecture: - Tight coupling

Problem 3:- HTML is not the only response type

Problem 4:- FlexibleCombination of view and data

Problem 5:- Making behind code a normal class for unit testing

So the solution is MVC?

What do we loose ?

Image 1

Request from a DAD

Thanks to Sanjana my daughter to create the above image. I would be thankful if you can share this image from FB which would boost her in becoming a cartoonist ahead. I want to just inform her how good she is in drawing and should think about it as career path.

BTW The above image will help you to visualize why MVC is better than webforms. As you read this Learn MVC step by step article ahead this image will help you to connect things together.


In this article I would be using two terminologies which will be used very frequently ASP.NET Web forms and ASP.NET MVC. Many developers think that ASP.NET is different from MVC. But the fact is MVC is an architecture coding style and ASP.NET a framework. If you are from the category who think ASP.NET is different from MVC then my honest suggestion is to first read this article to avoid any further confusion


If you watch the recent Microsoft agenda you will clearly see they are focusing on MVC , MVC and MVC. So the question is why is Microsoft so keen to dump a successful thing like ASP.NET Webform and persuade the Microsoft web development community to use ASP.NET MVC.

That’s what this article will focus on.

ASP.NET Webform behind code –boon and curse

If you closely watch ASP.NET webform technology it’s a RAD / VISUAL approach for web development. In other words developers drag and drop user controls on the designer and the VS tool codes in the behind code.

Image 2

So in other words when you drag and drop a button control on the designer a button object is created and developers can write code in the click event of the button object.

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

        protected void Button1_Click(object sender, EventArgs e)
            // Developers write code here

So when developers drag and drop these UI elements, double click to get the events on the front end, write logic in those events etc. At the back end smartly and quietly Microsoft code’s logic in the ASPX.CS partial class file.

Image 3

Now this partial behind code file was the key to success for delivering ASP.NET Webformprojects faster as developers where encapsulated from lot of technical details like events, delegates, HTTP protocol POST,GET, session management etc. You would probably like to read this article why Microsoft has partial classes ?and Microsoft UI success story.

But due to the way the behind code was positioned and invoked it has 5 serious problems. So let’s discuss those 5 problems and how MVC helps to address the same.

Problem 1 :- View based solution for Action based requirement

Websites at the end of the day are used by end users. End users come with a specific purpose to a website and they communicate their purpose by actions. For instance if somebody comes to shop on a shopping portal he will communicate his purposeusing actions like:-

  • Buy product.
  • Print invoice

Now these actions are communicated by button click , right click or through a browser URL etc. Due to this action based structure HTTP protocol was chosen for Web because it had actions like POST,GET,PUT,DELETEetc which can communicate the purpose of end users more clearly. That also makes REST a popular way of addressing end user request. So logically if we can map these actions to methods / functions of our program that would make more sense and also keep the architecture simple.

But Microsoft had no way out, they wanted to support RAD concept or we can term it as visual programming concept, so they ended up with a view based solution for an action based structure.

Image 4

So flow of request went something WEIRD like this for web forms( for visual’s see the above diagram):-

  • End user sends a request with action like HTTP POST / GET etc.
  • IIS webserver maps this request to a view.
  • View invokes the page life cycle, walks through events and then INVOKES THE APPROPRIATE ACTION.
  • Finally action put’s the RESULT IN HTML format and sends it to the end user browser.

Microsoft ended with a view based architecture for an action based requirement. So the architecture itself was not fitting logically to the end user’s action based approach. In other words if the end user sends a “Buy” action it first comes to a view like “Shopping.aspx” who in turn kicks of “Shopping.aspx.cs” which executes a complicated page life cycle which in turn executes the action which will fulfill the request of the end user.

Image 5

This is like hitting the bush. The end requests aregetting mapped to the actual action after a complicated page life cycle is completed. So how about we make itan action oriented architecturerather thanview oriented. Or I can rephrase it “HOW CAN WE MAKE ACTION FIRST STRUCTURE RATHER THAN A VIEW FIRST STRUCTURE ?”.

So how about hitting the action first and then the action picks up view. This would make the flow more logical and clear. That’s what exactly MVC architecture does. The first hit comes to an action which belongs in to a controller and then controller invokes the view with appropriate model.

Image 6

Problem 2:- Side effects of bad architecture: - Tight coupling

Once you start with a wrong architecture you end up adjusting things and then you end up with serious side effects. In this case the same was happening. The behind code which looks physically different in different files was never actually decoupled i.e. ASPX.CS cannot be separated from ASPX.

Image 7

In simple words I cannot attach “Customer.aspx.cs” with “CustomerDetailed.aspx” easily. The behind code is tightly coupled with view. It is not reusable.

If you ever analyze the quantity of behind code w.r.t to other layers of the project it’s huge in size with complex events. This makes the code unreadable and difficult to maintain from long term perspective.

So if we can change the view first based architecture to action first based architecture then we can reuse the same action code with different views. For instance if an end user sends an action “Display” it can invoke “DisplayDesktop.aspx” or it can display “DisplayMobile.aspx” depending on the type of device.

Image 8

So in the MVC action depending on situation we can invoke “MobileView” or “NormalView” , below is the sample code for the same. Now imagining achieving this in behind code of the Webform , difficult very difficult right.

public ActionResult Index(string DeviceType)
           if (viewType == "Mobile")
                return View("MobileView");
                return View("NormalView");

Problem 3:- HTML is not the only response type

Because of the tight coupling between view and code behind even the response type is fixed in webform , its by default HTML. If you wish to change it you need to play around with Content-type and “Response.End” methods etc which is quiet tedious.

If we create “Action” first structure then the action has all the luxury in the world to decide what kind of response type should go out. This makes our system more flexible in terms of same action with different outputs.

Below is a simple MVC action code which send’s JSON or HTML result depending on the value passed to the action. This kind of flexibility is difficult to achieve with webformview’s because they are meant to emit only HTML.

public ActionResult Index(string viewType)
            if (viewType == "JSON")
                return Json(new Customer(), JsonRequestBehavior.AllowGet);
                return View("DisplayCustomer", new Customer());

Problem 4:- FlexibleCombination of view and data

When we send response to a user it’s a combination of view (display) and data (model).Webform is a view first architecture so the view decides which model to connect making the view NOT SO flexible and also involving view in complex decision making. That clearly violates SRP of the SOLID principle read here more about SOLID Principles.

But if we make action first architecture then the first hits comes to the action and he picks the Model and the view to send different responses.

Image 9

In MVC action you can code something as shown below. You can pick up the same model and attach it with different view. For example in the below code we have taken “customerdata” model and attached with “DetailCustomer” view and the same model in other situation is attached with “Customer” view.

public ActionResult Index(string ViewName,Customer customerdata)
            if (ViewName == "Detailed")
return View("DetailCustomer",customerdata);
                return View("Customer",customerdata);

This kind of flexibility to achieve through Webform is very difficult because the invocation comes on the view itself and then you need write all decision making logic in the page life cycle and redirect to some other view not making the implementation so clean.

Problem 5:- Making behind code a normal class for unit testing

The behind code in webform is a very typical heavy and bulky weight partial class which cannot be instantiated in simple C# code straightforward. Remember the Webform screen inherits from the “Page” class. This page class cannot be created directly as it has lot of dependencies.

public partial class WebForm1 : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)


        public void Button1_Click(object sender, EventArgs e)
            Session["SomeSession"] = "Is this set";

Now the next thing which would come to your mind why would you want this page class to be instantiated. One of the place where I would like this page class to be instantiated is for unit testing. I would like to invoke the actions of the button click methods and test if the session variables are set properly,view states are properly etc.

But if you ever try to do that like as shown in the below code you will end with weird code as shown below. Watch out those ugly event args passed to the button click methods.

public void TestMethod1()
            WebApplication22.WebForm1 obj = new WebApplication22.WebForm1();

            obj.Button1_Click(this, new EventArgs());

And when you invoke it asks for more things which makes the UI Unit testing impossible.

Image 10

In case of MVC this becomes a normal class. A class which can instantiated in simple unit test project and you can test various aspects like session ,viewbag , tempdata in an easy way.

public class HomeController : Controller // ß this class is simple 
        public ActionResult Index()
            Session["SomeSession"] = "Is this set";
            return View("SomeView");

So the solution is MVC?

Image 11

So to change from a view based architecture to an action based MVC architecture we need to do the following structural changes ( The above image gives a visual view of the same):-

  • Move the behind code in to a controller class with all the events converted in to methods which can be termed as actions.
  • The middle layer becomes the model which provides data and business logic.
  • The view just does display,positioning and layouting.
  • The DAL and other layers do not change a lot as they have no connection with the behind code issue directly.

Image 12

So with MVC architecture we have the below three step flow:-

  • End user sends his request application. Application routes the request to the Controller. Controller is a logical entity which groups actions together.
  • Controller maps that request to a particular action.
  • Now action has two tasks to do first it needs to access appropriate data depending on the action and second that data has to be connected to the proper view. Action creates the model object and connects the model to the view to send the final response.

What do we loose ?

The biggest advantage of ASP.NET WebForm is RAD / VISUAL programming. Even though it’s a quick and dirty way of doing things it helps you to complete applications faster, make your clients happy and deliver on time. You can read this article which talks about what you will miss in MVC

The decision of Webforms was the right way for Microsoft in year 2000 because it wanted to migrate the VB6 , VF , VC++ developers whom they had addicted to RAD programming. I think Webform has achieved its goal for what it was created for now it’s time move toward’s better and logical architecture i.e. MVC .

So if you are convinced that MVC is the way forward you can Learn MVC in 2 days i.e. 16 hours using the below video.

Image 13

Also read and learn from Web Form vs MVC article.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Comments and Discussions

GeneralMy Vote of 5 Pin
Programming Tutorials by Tests4Geeks9-Jan-18 2:15
memberProgramming Tutorials by Tests4Geeks9-Jan-18 2:15 
QuestionShivprasad, well done/well written Pin
DurangoBPA17-Jun-16 10:50
memberDurangoBPA17-Jun-16 10:50 
QuestionI disagree Pin
cdengler8-Jun-16 9:20
membercdengler8-Jun-16 9:20 
QuestionFast development vs slow debug time js Pin
bertasoft18-May-16 23:02
memberbertasoft18-May-16 23:02 
AnswerRe: Fast development vs slow debug time js Pin
cdengler8-Jun-16 9:30
membercdengler8-Jun-16 9:30 
GeneralWebforms is not so bad without the "forms" part Pin
Member 1248332525-Apr-16 2:24
memberMember 1248332525-Apr-16 2:24 
The first thing I did when starting with webs=forms was to strip out the "forms" part by deleting
<form id="form1" runat="server">
in every new page. Then I never used the Controls, apart from the repeater. And then write the code manually and not use the design view.

That makes Webforms no longer a "view-based solution".

As for not being able to reuse code for "Customer.aspx" AND "CustomerDetail.aspx", I am not sure what you mean. A simple solution for any style of programming is to have a generic Customer class and have one page show more properties than the other. That is perfectly possible with Webforms.

Response types that are different from HTML are very easily done. What is the problem with Response.ContentType? What is more: it takes a lot of complicated code to have MVC return a generated image with the right contenttype. Also if data should be returned in either json, html, xml or whatever, then the convertion to that datatype should be the last step in order to maximize code-reuse. Paths to create the response should not divert immediately after receiving the request (as in the example given).

I could go on.

What I miss with MVC is anything more complicated then simple CRUD on data. Of course it is possible, but it is not easier (rather more complicated) then webforms-without-forms. Microsoft has started the Open Data Protocol (OData - the Best Way to REST[^]), to work with more complicated stuff than simple CRUD. It is interesting to see how this protocol moves the complexity from the server to the client. IMO that is a totally wrong direction. But it is the result of the limitation of MVC based on REST.

MVC might make simple CRUD easy. But that was not hard to begin with. MVC makes more complicated stuff harder. That more complicated stuff fits no longer in the REST approach, which opens MVC up to all kind of personal interpretations. That makes it messy. Maybe I missed that one. OData surely is not the way to go. Creating the queries on the client, is not only ugly, but it puts the BI in the wrong place, makes updates to the back-end impossible except when the clients (mobile apps?) are also updated.
SuggestionDo not expect too much from MVC. Otherwise, you would be very disappointed. Pin
Stefan Sze6-Mar-16 15:14
memberStefan Sze6-Mar-16 15:14 
GeneralRe: Do not expect too much from MVC. Otherwise, you would be very disappointed. Pin
bertasoft18-May-16 23:04
memberbertasoft18-May-16 23:04 
GeneralRe: Do not expect too much from MVC. Otherwise, you would be very disappointed. Pin
cdengler8-Jun-16 9:21
membercdengler8-Jun-16 9:21 
SuggestionMVC pattern is NOT a replacement of .NET Web Form! Do not expect too much from MVC. Pin
Stefan Sze6-Mar-16 14:58
memberStefan Sze6-Mar-16 14:58 
GeneralRe: MVC pattern is NOT a replacement of .NET Web Form! Do not expect too much from MVC. Pin
cdengler8-Jun-16 9:23
membercdengler8-Jun-16 9:23 
QuestionArtical Pin
Bhagyashree Chaudhari - Member 1047363413-Oct-15 0:15
memberBhagyashree Chaudhari - Member 1047363413-Oct-15 0:15 
QuestionWell explained Pin
Schatak1-Sep-15 18:44
professionalSchatak1-Sep-15 18:44 
GeneralMy vote of 5 Pin
Funny 201319-Jun-15 2:20
memberFunny 201319-Jun-15 2:20 
GeneralMy vote of 5 Pin
farshid_nv3-Jun-15 10:30
memberfarshid_nv3-Jun-15 10:30 
QuestionShivprasad ,You are Rocking Pin
yawxir14-Apr-15 18:58
memberyawxir14-Apr-15 18:58 
GeneralMy vote of 5 Pin
>Valero7-Jan-15 11:19
member>Valero7-Jan-15 11:19 
QuestionMVC ...Just not true Pin
TMags10-Dec-14 8:24
memberTMags10-Dec-14 8:24 
AnswerRe: MVC ...Just not true Pin
cdengler8-Jun-16 9:25
membercdengler8-Jun-16 9:25 
GeneralMy vote of 5 Pin
Akiii_Lethal7-Dec-14 18:25
memberAkiii_Lethal7-Dec-14 18:25 
GeneralMy vote of 5 Pin
Raul Iloc22-Oct-14 5:45
professionalRaul Iloc22-Oct-14 5:45 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun27-Sep-14 22:00
memberHumayun Kabir Mamun27-Sep-14 22:00 
QuestionWhere to find the other videos? Pin
Henke_D25-Sep-14 19:48
memberHenke_D25-Sep-14 19:48 
QuestionGreat Read Pin
GertClaassen23-Sep-14 22:00
memberGertClaassen23-Sep-14 22:00 
AnswerRe: Great Read Pin
aarif moh shaikh4-Oct-14 0:12
professionalaarif moh shaikh4-Oct-14 0:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 20 Sep 2014


119 bookmarked