SmoothFriction.nl

posts - 39, comments - 20, trackbacks - 0

ASP.NET MVC: Common viewdata

One issue I’ve heard a few times already when explaining ASP.NET MVC to others is how to deal with common viewdata which should be available to every page. Sure, you can simply add it to the viewdata in each and every controller action you call, but that’s a horrible violation of the DRY (Don’t Repeat Yourself) principle. It’s also very error-prone, because you’re very likely to forget to add it some time or another.

A more elegant solution to the problem is to have a base controller class which you will use for all your controllers. This is a no-brainer, really, as there’s almost always a case which warrants this solution.

A more elegant solution indeed!

The default Controller class used in ASP.NET MVC offers some interesting hooks for changing the behavior of your application. The ones we’re interested specifically are the event hooks, methods called ‘On…()’. In this case, we’ll make use of the OnActionExecuting() method. This method is called right before an action is executed. What we’re going to do is add a few things to the viewdata collection, so we can guarantee this data to be available at every point in the application.

First, let’s create a base class with the method mentioned overriden:

using System.Web.Mvc;

namespace CommonViewDataSample.Controllers
{
    public abstract class ControllerBase : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewData["MyViewData"] = "Something common here!!!";
            base.OnActionExecuting(filterContext);
        }
    }
}

Take note of setting the data in viewdata collection, which will now be available in any view you request.

Now, going by the sample ASP.NET MVC project that’s generated whenever you create a new MVC project, we’ll adapt the controllers in that project to make use of this base class:

In Controllers/HomeController.cs

public class HomeController

becomes

public class HomeController : ControllerBase

In Controllers/AccountController.cs

public class AccountController

becomes

public class AccountController : ControllerBase

Now you're set! In ANY view, masterpage, partial view or whatever, you can now use ViewData["MyViewData"] just like you'd use any other viewdata. There are more ways to reach this goal, but this is the simplest form other than putting your viewdata in every controller action, so I figured I’d touch this first. I will write about other methods do this later, so stay tuned!

Print | posted on Friday, October 02, 2009 1:50 AM | Filed Under [ c# asp.net mvc ]

Feedback

Gravatar

# re: ASP.NET MVC: Common viewdata

Thanks for the excellent review!
7/1/2010 6:43 PM | Liana

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 4 and 3 and type the answer here: