The World’s Leading Microsoft .NET Magazine
   
 
The .NET Addict's Blog

My Top Tags

                                                           

My RSS Feeds








I heart FeedBurner

Latest Diggs - Programming

Computers Blogs - Blog Top Sites

Site Hits

Total: 4,741,707
since: 19 Jan 2005

Using ASP.NET MVC Action Filters to Declare Reference Data for Views

posted Fri 02 Oct 09

When we all build websites, usually we're concerned with figuring out how we're going to get the major entities into the view. We want to know how we're going to handle the shopping cart or how we're going to get the customer record onto the page, etc. But, one of the little details that almost always comes back to bite us in the ass is the use of reference data.

Reference data is data that rarely changes, is frequently queried, and shows up in multiple places throughout the application. This might be anything from the list of companies currently trading on a particular stock market if you're building a financial web application or things like the list of countries, states, cities, counties, tax rules, and shipping tables if you're doing fulfillment of orders online.

The problem is we rarely think about reference data ahead of time, so what usually happens is our strategy for handling reference data becomes an ugly pile of spaghetti and we have some controls doing their own queries to get reference data and some pages doing it and some services - it's a mess.

It would be awesome if we could have our controller methods declare ahead of time what reference data the view is going to need and then the view will simply have that data when it renders - completely abstracting the manual fetching of reference data for dropdownlists and other lookups. This centralization of reference data handling also gives us the ability to control the cache lifetimes of reference data items individually.

Thankfully ASP.NET MVC lets us do this easily. All we have to do is create our own action filter attribute. For example, let's say we've got a Customer controller and we're building the Edit(int id) method. Our customer view model objects are normalized enough so that they have IDs on them for country, customer type, and membership type (totally contrived examples, don't diss my domain knowledge of CRMs...). A sample edit method might look like this:

[RequireReferenceData(ReferenceDataKey = ReferenceDataKeys.Countries)]
[RequireReferenceData(ReferenceDataKey = ReferenceDataKeys.CustomerTypes)]
[ReqiureReferenceData(ReferenceDataKey = ReferenceDataKeys.MembershipTypes)]
public ActionResult Edit(int id)
{
    Customer cust = customerRepository.GetCustomerByKey(id);
    return View(cust);
}

The beauty of this approach is that anyone reading your code will immediately know that the view being rendered is going to depend on having 3 different types of reference data lists made available, as well as the core Customer object itself. Compare how easy this is to read and maintain to a classic .ASPX page where you might have the countries lookup being loaded by a custom dropdown box and the customer types lookup being loaded by the page and the membership types being loaded by yet another pile of spaghetti elsewhere.

To create the RequireReferenceDataAttribute class, all you need to do is inherit from ActionFilterAttribute and override the OnExecuting method. In this method you would just fetch the reference data and store it in the ViewData dictionary like this:

context.Controller.Model.ViewData[ReferenceDataKey] = (data fetched from elsewhere...);

And then in your view you can do something like this:

<%= Html.DropDownList("CustomerTypeId", 
(IEnumerable<SelectListItem>)ViewData[ReferenceDataKeys.CustomerTypes]) %>

And you're all set. The main moral of this story is to never underestimate the power of action filters. With ASP.NET MVC, if you want your intent to be more declarative and you want your code to be more readable, chances are you're only a few lines of code away from where you want to be.

tags:        

links: digg this    del.icio.us    technorati    reddit

AddThis Social Bookmark Button




1. Matt left...
Tue 22 Dec 09 4:28 pm

I really like the idea of what you're sketching out here. Unfortunately I'm running into lots of gaps trying to create an implementation of it. Is this something you've actually done or was this just a thought exercise?

Either way it seems to be the best sounding theory on how to handle reference data in mvc so far.


Tag Related Posts

Html.JqGrid - Cleaning up your jqGrid Code

Tue 22 Dec 09 8:46 P GMT-05
tags:              

How to Build your First Azure-Powered MVC App

Tue 29 Sep 09 2:16 P GMT-05
tags:        

ViewState is the Froo-It of the Dev-Il

Wed 23 Sep 09 3:09 P GMT-05
tags:      

Fix for Minor Bug in ASP.NET MVC New Project Template

Mon 04 May 09 2:48 A GMT-05
tags:      

NYC SharePoint Developer Needed

Mon 12 May 08 12:09 P GMT-05

Scott Guthrie Updates the ASP.NET MVC Roadmap

Wed 13 Feb 08 3:49 P GMT-05
tags:    

Volta is to Ajax what Tums is to my Stomach

Wed 30 Jan 08 4:11 P GMT-05

ASP.NET 3.5 Extensions Preview Released

Mon 10 Dec 07 2:10 P GMT-05

Microsoft unveils an MVC framework for ASP.NET

Mon 08 Oct 07 12:58 P GMT-05
tags:      

Exploring the MVC Pattern in WPF

Tue 10 Apr 07 12:51 P GMT-05
tags:                      

ASP.NET Ajax v1.0 Beta

Fri 27 Oct 06 6:17 P GMT-05
tags:      

ASP.NET vs Ruby on Rails : Round 2 (Agility)

Thu 05 Oct 06 11:02 A GMT-05
tags:                      

ASP.NET vs Ruby on Rails : Round 1

Wed 04 Oct 06 1:37 P GMT-05
tags: