Pass data to your master page(ASP.NET MVC)

By nunos.

The master page is not a common view and we have no specific controller action methods for it. In fact, the master page is rendered every time we return a view from an action method. should I pass the data in every action method?

I absolutely refused to add a line of code to every action method passing that information in the ViewData dictionary. Not only it’s boring to keep repeating myself, it’s also against the DRY principle (Don’t Repeat Yourself).

So what to do? I’m sure there are other solutions but this one seems very elegant and in line with the best practices: we use inheritance.

Create a new class under your controllers folder and use the following code:

public class MySiteController : Controller

{

    public NorthwindEFEntities nw;

 

    public MySiteController()

    {

        nw = new NorthwindEFEntities();

        ViewData["categories"] = from c in nw.Categories

                                 select c;

    }

}

Notice that this new class inherits from the Controller class, just like any other controller you’d create. The trick now is to change your controllers to inherit from MySiteController instead, so that the category information is injected in every action method execution.

public class HomeController : MySiteController

{

    public ActionResult Index()

    {

        return View();

    }

}


So, we can implement our action methods as usual without worrying with the category information as that is being already passed on through the ViewData dictionary.

Of course, we need to change the master page so that it renders this information. Locate the ul element named “menu” and change it to this:

<ul id="menu">             

<% foreach (var c in (IEnumerable<MvcApplicationNamespace.Models.Category>) ViewData["categories"])

   {%>

    <li><%= Html.ActionLink(c.CategoryName, "Category", "Home", new { id = c.CategoryID },null) %></li>

<%} %>

</ul>

posted on 2010-07-26 17:10  武汉虫虫  阅读(408)  评论(1编辑  收藏  举报

导航