ASP.NET - WebForms versus MVC Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/series/mvc-compared-to-webforms/ Production Grade Technical Solutions | Data Encryption and Public Cloud Expert Thu, 12 Apr 2012 20:32:55 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://www.anujvarma.com/wp-content/uploads/anujtech.png ASP.NET - WebForms versus MVC Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/series/mvc-compared-to-webforms/ 32 32 Building Rapid, Testable Web-Forms– Conclusion https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93-conclusion-comparing-the-mvc-framework-with-asp-net-webforms/ https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93-conclusion-comparing-the-mvc-framework-with-asp-net-webforms/#respond Thu, 14 Jul 2011 22:20:24 +0000 http://www.anujvarma.com/?p=269 Conclusion If your application relies on rich user controls (either 3rd party or your own in-house controls), WebForms may be the best option. The reports of WebForms being un-testable are […]

The post Building Rapid, Testable Web-Forms– Conclusion appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Conclusion

If your application relies on rich user controls (either 3rd party or your own in-house controls), WebForms may be the best option. The reports of WebForms being un-testable are greatly exaggerated – and one can easily write unit tests around webforms (for e.g. – using NUnitForms).

The greatest driving factor for doing MVC is Test Driven Development (TDD) – and while MVC does make it a piece of cake to write comprehensive unit tests, it is not entirely difficult to do the same in the webform world. Some other reasons to adopt MVC would be:

  • To support platforms with disparate display types – e.g. Mobile and Desktop and Web. Using heavy winforms/webforms controls here would mean a complete re-write of the presentation layer to support mobile displays. With MVC, the view is cleanly separated out – making it easy to write a ‘ mobile view ‘ and a ‘desktop view’. This is perhaps the biggest motivator to use mvc ( more so than testability – since UI testability can be achieved with WINFORMS/webforms as well.

  • To build SEO based URLs

  • To have more control over the generated HTML – allowing easier integration with jQuery and other javascript frameworks.

  • Open Source Technology

The choice depends on the nature of your application. Personally, the types of applications I work with are all heavy on user controls – and WebForms lends itself to building such apps. Being a TDD fanatic as well, I resort to writing NUnitForms tests for my webforms. Regarding some of the other shortcomings of webforms, there are simple workarounds for each of them (e.g. ViewState can be disabled,  ClientIds can be controlled in ASP.NET 4.0 onwards). If I build an app using just MVC and have to revisit it later to add a sophisticated UI control (such as a datagrid etc.) to the application, I may have a lot of work ahead of me. On the flip side, if I already have a WebForms app, there is little that can be thrown at it that will call for a complete overhaul of the existing architecture.

The post Building Rapid, Testable Web-Forms– Conclusion appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93-conclusion-comparing-the-mvc-framework-with-asp-net-webforms/feed/ 0
Building Rapid, Testable Web-Forms–Comparing the MVC Framework with ASP.NET WebForms https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93comparing-the-mvc-framework-with-asp-net-webforms-2/ https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93comparing-the-mvc-framework-with-asp-net-webforms-2/#respond Thu, 14 Jul 2011 22:12:21 +0000 http://www.anujvarma.com/?p=265 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 […]

The post Building Rapid, Testable Web-Forms–Comparing the MVC Framework with ASP.NET WebForms appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
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 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.

MVC Advantages (over asp.net webforms)

1. Testability : 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. No Postbacks, No ViewState, No 1-1 Mapping between URL and Physical File. 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 data.

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, we 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.  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.

In the MVC world, we do not have to worry about the ViewState or Postback any longer. This also leads to ‘No Client Ids Pollution’. The client side HTML contents are cleaner since there are no “client side IDs”.

3.  No databinding – which leads to complete control over the HTML. Instead, the data is placed in a model class and retrieved using a strongly typed view that has direct access to that model.

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

5. 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 provider architecture, authentication and authorization plumbing, membership and roles, caching, session management and more.

6. URL routing mechanism – the MVC framework supports a powerful URL routing mechanism that helps to build more searchable URLs in your application, assisting 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.

When To Use ASP.Net MVC

Unit Testing

This is possibly the most significant reason to consider using ASP.NET MVC.  Whereas web forms have been notoriously difficult to test (due to the page event lifecycle), the MVC framework lends itself to unit testing.  

Control and Extensibility over the HTML

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 WebForms, the generated HTML is usually not a candidate for light reading. It is ugly – cluttered – and overly prosaic. Web controls generate ids and hidden fields that are difficult to apply CSS styling (or javascript code) to.   MVC, on the other hand, forces you to generate cleaner HTML.  There aren’t any datagrids, repeaters, listboxes etc. that generate markup for you. It’s just the HTML along with a few extension methods.

When not to use ASP.Net MVC

  • If your application relies heavily on 3rd party controls

There are lots of 3rd party controls and extensions for WebForms in the marketplace (see my post on using Syncfusion Grid Control for grid display on steroids).  There is so much out there that you can do quite a bit without a whole lot of code.

  • If you do not want to build on top of the MVC Framework

ASP.NET MVC has very few features.  It has some basic url helpers, html helpers, and ajax helpers.   There is very little ‘out of the box’.

The post Building Rapid, Testable Web-Forms–Comparing the MVC Framework with ASP.NET WebForms appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93comparing-the-mvc-framework-with-asp-net-webforms-2/feed/ 0
Building Rapid, Testable Web-Forms–Hello World with ASP.NET MVC https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93hello-world-with-asp-net-mvc/ https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93hello-world-with-asp-net-mvc/#respond Thu, 14 Jul 2011 21:45:02 +0000 http://www.anujvarma.com/?p=260 “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 […]

The post Building Rapid, Testable Web-Forms–Hello World with ASP.NET MVC appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
“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>



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”, we can start comparing ASP.Net MVC versus regular webforms.

The post Building Rapid, Testable Web-Forms–Hello World with ASP.NET MVC appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93hello-world-with-asp-net-mvc/feed/ 0
Building Rapid, Testable Web-Forms–Introducing ASP.NET MVC https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93comparing-the-mvc-framework-with-asp-net-webforms/ https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93comparing-the-mvc-framework-with-asp-net-webforms/#respond Thu, 14 Jul 2011 21:37:17 +0000 http://www.anujvarma.com/?p=257 The goal of web-development is to build web-forms fast – and build web forms that are testable. There are currently two competing technologies for building web-forms – Classic ASP.NET (WebForms) […]

The post Building Rapid, Testable Web-Forms–Introducing ASP.NET MVC appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
The goal of web-development is to build web-forms fast – and build web forms that are testable. There are currently two competing technologies for building web-forms – Classic ASP.NET (WebForms) – and MVC (ASP.NET MVC) – which is radically different from WebForms. WebForms win hands-down in terms of rapidity of development. MVC wins when it comes to writing tests and providing code coverage for the web forms.  In this series, we explore ASP.NET MVC in detail – and provide insight into whether it makes sense to adopt this technology for your next web application.

Goals of the 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

Ingredients of MVC

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).
  • "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.
  • "Views" in a MVC based application are the components responsible for displaying the application’s user interface.  Typically, the model data is used for creating this UI (for example: we might create an Product "Edit" view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).

Key Benefit of MVC

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.



The post Building Rapid, Testable Web-Forms–Introducing ASP.NET MVC appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/building-rapid-testable-web-forms%e2%80%93comparing-the-mvc-framework-with-asp-net-webforms/feed/ 0