To MVC or not to MVC

Wednesday, July 28, 2010

ASP.NET MVC is quickly gaining ground over regular ASP.NET webforms. This article discusses the pros and cons of the two competing development models and identifies what types of applications may not be well suited for MVC.

Before we start with pros and cons of ASP.Net MVC and ASP.Net Web Forms here’s a brief introduction on ASP.Net MVC

Introduction

MVC is a framework methodology that divides an application's implementation into three component roles: models, views, and controllers.

  • "Models" in a MVC based application are the components of the application that are responsible for maintaining state.  Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).
  • "Views" in a MVC based application are the components responsible for displaying the application's user interface.  Typically this UI is created off of the model data (for example: we might create an Product "Edit" view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).
  • "Controllers" in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI.  In a MVC application the view is only about displaying information - it is the controller that handles and responds to user input and interaction.

One of the benefits of using a MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application.  Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated.

The MVC pattern can also help enable red/green test driven development (TDD) - where you implement automated unit tests, which define and verify the requirements of new code, first before you actually write the code itself.

Goals of the ASP.NET MVC Framework

Some of the stated goals of the framework are:

  • Enable clean separation of concerns
  • Be testable by default
  • Support Inversion of Control (IoC) containers and third-party view engines
  • Support customization of URLs
  • Leverage existing ASP.NET features
  • Support static and dynamic languages

How to Say “Hello World” with ASP.Net MVC

This is a simple hello world example with ASP.NET MVC, to help you build your first application step by step.We’ll create a web application with two additional views - the first will ask for your name, and when you submit it you’ll get a greeting message in the 2nd view. Lets start:

1. Download and install ASP.NET MVC

2. Create a new ASP.NET MVC Web Application, Call it MVCHelloWorld

mvcnewproj-thumb

Click “OK” and the project is created. Lets see what files are created with it: a default Controller - HomeController with two methods, a view for each of the methods, the Site.Master - similar to asp.net master page, Global.asax - this is where you configure routing and a few additional files (browse through to see…).

3. Add Methods in the Home Controller

   1:  public ActionResult SayHello()
   2:  {
   3:      ViewData["Title"] = "Say Hello";
   4:   
   5:      return View();
   6:  }
   7:   
   8:  public ActionResult Hello(string userName)
   9:  {
  10:      ViewData["UserName"] = userName;
  11:      return View();
  12:  }

The Hello method will store user name in the ViewData and redirect to the Hello view.

4. Add the SayHello and Hello views (MVC View Content Page) in Views/Home folder:
mvcaddcontentpage
Add this code to SayHello.aspx

   1:  <asp:Content ID="sayHelloContent" ContentPlaceHolderID="MainContent" runat="server">
   2:      <div>
   3:          <h2>
   4:              Say Hello</h2>
   5:          <form id="frmSayHello" action="<%= Url.Action("Hello", "Home")%>"
   6:                onsubmit="return SayHi()">
   7:              <span>Your Name:</span>
   8:              <input id="txtUserName" name="userName" type="text" />
   9:              <input type="submit" value="Go" />
  10:              <span id="errorMsg" style="display:none; color:Red">Invalid Name!</span>
  11:          </form>
  12:      </div>
  13:   
  14:      <script type="text/javascript">
  15:      function SayHi()
  16:      {
  17:          var txt = document.getElementById('txtUserName');
  18:          var userName = txt.value ;
  19:   
  20:          if (userName.length == 0)
  21:          {
  22:              document.getElementById('errorMsg').style.display = '';
  23:              txt.focus();
  24:              return false;
  25:          }
  26:   
  27:          return true;
  28:      }
  29:      </script>
  30:   
  31:  </asp:Content>


Lets define a form for the “Hello” action, and a javascript function to validate input on client side.

In the Hello.aspx file just use the ViewData prepared by the Controller:

   1:  <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
   2:      <h2>Hello <%= Html.Encode(ViewData["UserName"]) %>!</h2>
   3:  </asp:Content>

5. Add another menu item in Site.Master:

   1:  <li>
   2:      <%= Html.ActionLink("Say Hi", "SayHello", "Home")%>
   3:  </li>

6. In Global.asax add a route to the “Hello” method and change the default route to the “SayHello” method

   1:  public static void RegisterRoutes(RouteCollection routes)
   2:  {
   3:      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
   4:   
   5:      routes.Add(
   6:          new Route("Home/Hello",
   7:          new RouteValueDictionary(
   8:              new { controller = "Home", action = "Hello" })
   9:              , new MvcRouteHandler()));
  10:   
  11:      routes.MapRoute(
  12:          "Default",                                              // Route name
  13:          "{controller}/{action}/{id}",                           // URL with parameters
  14:          new { controller = "Home", action = "SayHello", id = "" }  // Parameter defaults
  15:      );
  16:   
  17:  }
Thats it, you are all done.


Now that we have seen how to say “Hello World”, lets see ASP.Net MVC advantages-

ASP.NET MVC advantages over asp.net webforms

1. The ASP.NET MVC framework does not use the ASP.NET postback model for interactions with the server. Instead, all end-user interactions are routed to a controller class. This maintains separation between UI logic and business logic and facilitates testability. As a result, the ASP.NET view state and ASP.NET page life-cycle events are not integrated with MVC-based views.

2. More Distinct Separations between the M-V-C

Rather than the traditional ASP.NET Web Forms under which the controller and view are within a page (the .aspx corresponds to the View and .aspx.cs to Controller), by introducing a new REST model, each page in ASP.NET MVC is split into two distinct components -- Controller and View -- that operate over the same Model of data. For a clearer understanding, Figure 2 shows the relationships of the Model, View, and Controller in the sample application provided with this article series.

Also, the MVC framework doesn't consider any URL as the endpoint to a physical server file to parse and compile to a class. In ASP.NET Web Forms, you have a 1:1 correspondence between a URL and a resource. The only exception to this rule is when you use completely custom HTTP handlers bound to a particular path.

In the MVC framework, a URL is seen as the means to address a logical server resource, but not necessarily an ASPX file to parse. So the URLs employed by the pages of an MVC framework-based application have a custom format that the application itself mandates. In the end, the MVC framework employs a centralized HTTP handler that recognizes an application-specific syntax for links. In addition, each addressable resource exposes a well-known set of operations and a uniform interface for executing operations.

So, in the MVC world, you do not bother with the ViewState and Postback any more.

3. And also, the client side HTML contents will become clean without “client side ID pollution” troubling you.

4. Complete control over the HTML.  No databinding. Instead, place data in a model class and use a strongly typed view to have direct access to that model.

5. TDD – the MVC framework brings better support to test-driven development.

6. Extensible and pluggable – the MVC framework components were designed to be pluggable and extensible and therefore can be replaced or customized
easier then Web Forms.

7. Full control over application behavior – the MVC framework doesn’t use ViewState or server based forms like Web Forms. This gives the application developer more control over the behaviors of the application and also reduce the bandwidth of requests to the server.

8. ASP.NET features are supportedMVC framework is built on top of ASP.NET and therefore can use most of the features that ASP.NET include
such as the providers architecture, authentication and authorization scenarios, membership and roles, caching, session and more.

9. URL routing mechanism – the MVC framework supports a powerful URL routing mechanism that helps to build a more comprehensible and
searchable URLs in your application. This mechanism helps to the application to be more addressable from the eyes of search engines and clients and can
help in search engine optimization.

MVC Disadvantages

  1. User controls (and server controls) are much harder to use in MVC world.
  2. DataBinding on controls is much harder
  3. Need to download and install ASP.NET MVC (installs some dlls in the gac)
  4. Any public method in a controller is exposed as a controller action. You need to be careful about this. This means that any public method contained in a controller can be invoked by anyone with access to the Internet by entering the right URL into a browser. e.g. wwwxyz.com/shop/delete/12  will delete shop with ID 12.
Web Forms Web Application Advantages

The old ASP.NET Web Forms framework is a mature framework that is being used in a lot of applications and web sites. The advantages of Web
Forms are:

  1. State Management – in Web Forms state management is more easier. The use of ViewState or server based forms simplify the state management
    but reduce the control over the application behavior.
  2. Event driven model – the Web Forms uses an event model that helps to develop a more event driven application. You can wire to a lot of
    events that are supported by the framework through controls and your pages.
  3. Server Controls – the Web Forms approach has a massive control libraries that can be used to build your application. On the other hand, the MVC framework doesn’t currently have a lot of controls that can help to build a more rich application and therefore you’ll have to build them yourself.
  4. Rapid development – it is faster to develop applications in the Web Forms approach. The reasons for that are the support for components like server controls or the page class that make it easier to develop (but brings a lot of cons which are some of the advantages of MVC framework).

Web Forms Web Application Disadvantages

  1. Web Forms have some severe set backs, most notably is that we are limited to a single Form tag on a page which requires the entire contents of the page to be posted back and processed by the server, even if the only change is the selection of an item in a drop down menu (where the drop down menu needs to auto-postback to allow us to perform some other kind of logic). This is a HUGE disadvantage as the developer can not process parts of the page in the same manner we would have using normal HTML elements and multiple form tags which enable partial-page processing. 
  2. Another major disadvantage is VIEWSTATE, Microsoft's answer to page state management. Viewstate stores just that, the state of elements on the page, so that the developer no longer has to specifically handle this on a postback. However VIEWSTATE bloats the page, often enormously, and becomes a major problem when a page contains lots of controls and data, causing huge performance lags as all this data must be passed back and forth to the server on each postback which is only further impacted by the "single form tag" problem.

When To Use ASP.Net MVC

To Unit Test

This, in my opinion, is the most compelling reason to use ASP.NET MVC.  When it comes to unit testing, ASP.NET MVC simply blows ASP.NET web forms out of the water.  It's not even close.  Whereas ASP.NET web forms requires you to jump through all sorts of hoops to test around the page event lifecycle, the ASP.NET MVC framework practically begs to be tested.  

There's a reason why the biggest ASP.NET MVC supporters also tend to be TDD proponents; it's because ASP.NET MVC actually allows for TDD.  Personally, I think this is where all the zeal comes from.  Simply put: it's really, really easy to do Unit Testing in ASP.NET MVC.

To Gain Control and Extensibility

ASP.NET MVC gives you more control and extensibility options than ASP.NET web forms.  You get complete control over the page request lifecycle and the ability to substitute out several key pieces of the framework (e.g. view engine, routing, etc.), none of which is possible with ASP.NET web forms.

In addition to this, you also gain full control over the rendered HTML.  In general, the rendered HTML from ASP.NET web forms applications is atrocious.  The web controls it utilizes generate garbage ids and hidden fields galore that not only hamper the performance of a site, but also make CSS styling and Javascript development a pain.  ASP.NET MVC forces you to be more in tune with your HTML.  There aren't any repeaters or datagrids that magically generate markup for you.  There aren't any hidden fields to persist state for you.  It's just you, the HTML, and a few extension methods (which you don't even have to use).

When not to use ASP.Net MVC

If you are not familiar with the concept of polymorphism

ASP.NET MVC makes use of interfaces, abstract classes, virtual methods and some psuedo-AOP.  If you are not well-versed with these object-oriented concepts, then the framework might not be very friendly for you.  While WebForms uses the template method to give the developer some well-defined places to put code, the MVC framework specifies an array of extension points that leverage the power of object-oriented programming to add on and extend the framework.

If you do not want to build on top of framework

ASP.NET MVC has very few features.  It has some basic url helpers, html helpers, and ajax helpers.  Even these are light on maintainability and are very basic.  They leverage string literals to do their job.  Without custom abstractions built on top of these, it will be difficult to develop a maintainable application that is more than a handful of pages. 

If you rely heavily on 3rd party controls

There are lots of 3rd party controls and extensions for WebForms in the marketplace.  There is so much out there that you can do quite a bit without a whole lot of code.  ASP.NET MVC doesn’t have lots of extensions in the marketplace

Conclusion

The choice whether ASP.Net MVC is better or ASP.Net Web Forms would vary with people. If you want more control over the HTML or you want Test Driven Development (TDD), or you care about web standards, accessibility, or you want to build SEO based URLs, you can choose MVC model. If you want rich controls and state oriented event-driven web development, you can choose Web Forms model. If you feel more comfortable with MVC, choose that model and you feel Web Form model is more comfortable, choose that model. Both are just choices. If you start your career with ASP.net Web Forms and do not have full knowledge of Web, it will be very difficult moving to MVC model.

ASP.Net MVC’s technical features as well as the open source nature have attracted me a lot.The MVC model allows full control over the HTML and enables Test Driven Development (TDD). We can easily integrate with jQuery and other JavaScript frameworks with MVC. Using extension methods of C# 3.0, we can make powerful and rich HTML helper methods. I believe that testability, refactoring capability and maintainability are the main factors for a successful project. The MVC model allows to build highly testable, maintainable loosely coupled applications with good practices such as TDD, Separation of Concerns (SoC) and Dependency Injection (DI).

click here to go to ASP.Net MVC Tutorials

Tags:
Filed Under:

Comments