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.
Essentially the solution is very simple and involves creating a new abstract class of Controller called "CommonController" (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
Create a new controller, and use this instead:
public abstract class CommonController : Controller
Notice the "abstract" keyword in there, that's the only difference.
Now, in your actual Controllers, you need them to inherit this CommonController instead of the normal Controller, so instead of using:
public class HomeController : Controller
You need to use:
public class HomeController : CommonController
Now, in this class instead of the usual ActionResult methods, you'll have a void method set up like so:
public void GlobalController() {
ViewData["MyVariable"] = value;
}
Now that you've done that, all of the ViewData variables set in CommonController will be available to the Views returned from your Controller.
Simples!
Be the first to comment
Both fields are required.
This is my personal website where I talk about a whole load of different stuff, from 