.Net Development & General Tech Related News

ASP.NET MVC – Passing ViewData to a MasterPage

January 12th, 2010 Posted in .Net, ASP.NET MVC, ASP.Net, C#

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!


Kick It on DotNetKicks.com
Share this Post:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • Reddit
  • StumbleUpon
  • TwitThis
No TweetBacks yet. (Be the first to Tweet this post)

Technorati Tags:

Tags:

Post a Comment