Hire Me

Incorporating common ViewData into multiple Controllers in ASPNET MVC without duplication

Incorporating common ViewData into multiple Controllers in ASPNET MVC without duplication

Posted on Sunday, February 28, 2010 at 9:49 PM into csharp code by Steve Woods

In this short tutorial I will show you how to make common ViewData information available to your Views in ASP.NET MVC, without having to duplicate ViewData[] variables in each seperate controller

During my learning phase of ASP.NET MVC, one of my bugbears was that when I wanted to display information from my database on multiple Views, I had to load that data in during the running of each Controller Action, and essentially duplicating code across multiple Controller Actions.

For instance, if I wanted a list of categories for my products on the Master Page, in each controller I might have something like:

ViewData["Categories"] = (from c in db.Categories 
    where c.isEnabled = true 
    orderby c.Title descending 
    select c);

If you imagine that code repeated throughout the perhaps 20 or 30 Controller Actions within the application, you can see the kind of problems you'd have maintaining it - it's a violation of the DRY (Don't Repeat Yourself) principle for starters.

The solution

Essentially the solution is very simple and involves creating a new abstract class of Controller called "GlobalController" (or XController, or whateverController you like) and placing the code in there instead of your actual controller.

When you create a controller normally, this is the code you use:
public class HomeController : Controller

The Code

Notice the "abstract" keyword in there, that's the only difference. The Viewdata is contained within the class Constructor - place your ViewData code in there with any values you need throughout the application.
Now, in your usual Controllers, you need to make them to inherit this GlobalController abstract class instead of the normal Controller class, so instead of using:

public class HomeController : Controller

You need to use:

public class HomeController : GlobalController

Now that you've done that, all of the ViewData set in GlobalController constructor will be available to your views.




Please consider what you post!
Chillax if you're angry.