MVP Corner: Use the ASP.NET MVC Framework to Write Web Apps without ViewState or Postbacks

n October 6, 2007, Scott Guthrie officially unveiled the ASP.NET MVC Framework at the AltNetConf in Austin, TX. It’s interesting he chose to present it for the first time at this particular venue because the target audience contained some of the most avid open-source software users including users of the MonoRail MVC framework. What could have been perhaps his most hostile and critical audience turned into happy campers after he presented the details and goals of ASP.NET MVC.

Why Model-View-Controller?
ASP.NET has been the odd man out in the web world. While you’ll find several MVC frameworks in the Java space, ASP.NET’s default model has always been Web Forms. Ruby on Rails framework has captured great fanfare thanks in no small part to its core MVC architecture. For .NET developers, MonoRail has so far been the only MVC alternative to web applications. With all the focus on MVC, one might wonder why? Mode-View-Controller is a mature, proven architecture for the presentation layer. It’s applicable in fat client applications as well as web applications. When applied to web applications, the twist is that the controller lives for a single HTTP request and then goes away. Fat client controllers are more stateful and live for the life of the screen, responding to user input.

With Microsoft’s announcement of the shift of ASP.NET from Web Forms to MVC, buzz abounds on the blogosphere about how great of an improvement this will be for web applications built on the .NET platform.

What’s Wrong with Web Forms?
Many developers agree that the Postback and ViewState model employed by Web Forms causes pain and heartache. A quick Google search for “ViewState problem” and “Postback problem” brings back 300,000+ and 400,000+ results, respectively. Scott Guthrie reports that a lot of customers have voiced concerns about the Web Forms model and had requested an MVC framework to simplify web application development. In this author’s opinion, the main problem with Web Forms is that it employs an elaborate scheme to hide the developer from the stateless nature of HTTP. With event handlers and the page lifecycle, the developer falls into managing state with ViewState and Postbacks, and when employed in the reality of the stateless web, the model becomes fragile and has problems scaling with complexity.

Goals of the ASP.NET MVC Framework
The MVC framework started as a prototype created on one of Mr. Guthrie’s airplane rides. It is still in prototype stage with the hopes of reaching CTP status before the end of 2007. 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

With a change in architecture, a few constraints are unavoidable; this author thinks of those as benefits but they mean a change for existing applications, nonetheless:

  • Views will no longer use ViewState.
  • Views will not use Postbacks or Postback events.
Editor’s Note: This article was first published in the January/February 2008 issue of CoDe Magazine, and is reprinted here by permission.

Let’s Dig into Some Code!
The simplest way to get a web page up and running on the new MVC framework is to create a route and a class that implements the IController interface. First I’ll show you how to create a route to map http://www.partywithpalermo.com/rsvp to an RsvpController.

   --/Global.asax.cs File   public class Global : HttpApplication   {      protected void Application_Start(object          sender, EventArgs e)      {         Router.Routes.Add(new Route("rsvp",             "/rsvp/[action]",             typeof(RsvpController)));      }   }      --/Controllers/RsvpController.cs File   public class RsvpController : IController   {   public void Execute(HttpContext context,       RouteData routeData)      {         context.Response.Write("

Thanks for RSVPing

"); } }

Note that you must have the following set up in web.config:

                                                                                     

The ControllerModule class creates a handler for the request; therefore, there is no need to configure the handler in the web.config file. If you’re running on IIS 6 or higher, you must enable wildcard mappings. On IIS 5, create a “*” mapping to ASP.NET, so that every request gets routed through the ASP.NET engine. By default, IIS will try to serve requests that appear to be at the directory level.

Note that I can match a URL with the controller that should handle it. I’m not required to use a view but to merely implement an Execute method. Now let me take it further and take advantage of the Controller base class. I’ll extend the controller so that it can list all attendees who have RSVP’d.

Extending the Controller
A key change is that RSVPController inherits from the Controller base class. The base class performs the Execute() method and wires up actions. Using the ControllerActionAttribute declares that the Index() method should be exposed as an action (Index() is the default action).

   --/Controllers/RsvpController.cs File   public class RsvpController : Controller   {      [ControllerAction]      public void Index()      {         RenderView("RsvpList");      }   }

For example’s sake, I’ll change the URL to be http://www.partywithpalermo.com/rsvp/list where list will be the action.

   --/Controllers/RsvpController.cs File   public class RsvpController : Controller   {   private IAttendeesRepository repository      = new AttendeeRepository();      [ControllerAction]      public void List()      {         IEnumerable attendees =            repository.GetAttendees();         RenderView("RsvpList", attendees);      }   }

Note the RenderView() method in the preceding code. The RsvpList string argument denotes the name of a view in the /Views folder in the web application. It will look for the file /Views/RsvpList.aspx, load it, and render it. To retrieve the Attendees the code uses an IAttendeesRepository. The page code sets a property bag called ViewData with the objects that need to go to the view. In this case there’s a single object but you can set several because ViewData is an IDictionary unless overridden.

   --/Views/RsvpList.aspx File   <%@ Page Language="C#"      AutoEventWireup="true"      CodeBehind="RsvpList.aspx.cs"      Inherits="PartyWithPalermo.Website.Views.     RsvpHome" %>   <%@ Import namespace="PartyWithPalermo.     Domain.Model"%>   <%@ Import namespace="PartyWithPalermo.     Website.Controllers"%>                  Party with Palermo                         <% foreach (Attendee attendee in               ViewData) { %>                      <% } %>       
Name Website Comment
<%=attendee.Name %> <%=attendee.Website %> <%=attendee.Comment %>
--/Views/RsvpList.aspx.cs File public partial class RsvpHome : ViewPage> { protected void Page_Load(object sender, EventArgs e) { } }

The only difference from the code-behind is that it inherits from ViewPage instead of merely Page. By declaring the generic form of ViewPage you have strongly-typed ViewData, and you can create a presentation DTO to hold any information that needs to be passed to the view. You’ll get IntelliSense when binding objects to the view. Table 1 shows the view rendered to the browser.

Name

Web site

Comment

Jeffrey Palermo

http://www.jeffreypalermo.com

Please RSVP, and you’ll be added to this list!

Homer Simpson

http://www.simpsons.com

Doh!

Bart Simpson

http://www.simpsons.com

Don’t have a cow.

Table 1: View rendered to the browser.

Note how simplified this view is. This technique allows you to leverage the raw power of HTML (and still use server controls) without ViewState, Postbacks, or a server-side form wrapping the entire page.

Conclusion
This brief overview of Microsoft’s new ASP.NET MVC framework barely scratches the surface of its capabilities. I did not cover mapping query string or form variables into controller actions, output caching, etc., but the framework has all these covered. The ASP.NET MVC framework also supports advanced scenarios, including Inversion of Control (IoC) container creation of controllers, and loading UserControls as a partial view. The framework is still in the prototype stage, but when it hits CTP status in a month or so, check out my blog for more information.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS