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

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


Web site


Jeffrey Palermo

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

Homer Simpson


Bart Simpson

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.

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:
5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time