If like me you are using ASP.NET MVC for some of your web applications these days and use MasterPages within them, then you may have come accross the need to pass ViewData to the MasterPage. For example, this might be for a dynamically generated navigation bar.
When I first started using MVC, I simply passed the ViewData required for the MasterPage along with every action, but even with a small site, this was a lot of code replication.
To solve this problem, we can create an ApplicationController class which inherits from the Controller class we all know and love. Your applications’ controllers then in turn simply inherit from this new ApplicationController.
Below is a simple example of an ApplicationController.
namespace MvcSite.Controllers { public abstract class ApplicationController : Controller { private MyEntities _dataContext = new MyEntities(); public MyEntities DataContext { get { return _dataContext; } } public ApplicationController() { ViewData["categories"] = DataContext.Categories.ToList(); } } }
Hope this helps someone else as well. Certainly removed a headache for me!
1 comment
No ping yet
sree says:
November 30, 2011 at 8:50 am (UTC -5)
Thanks for this Solution. I found this in another site as well..but I am just replicating what you mentioned here and my masterpage is not seing VIEWDATA. I keep getting ViewData is not available in current context..
Any ideas?