Search code examples
asp.net-mvc-2dynamic-data

ASP.NET MVC, partial views and data


Can anyone elaborate on why you'd define ViewData["MenuData"] on every action for something like a dynamic menu?

I have a simple partial view which renders a menu, I render this menu from within a master page. This is intutive for me comming from ASP.NET WebForms, but the only way for me to populate the menu is to pass ViewData["MenuData"], but then I have to do this in every controller action. It does feel a bit stupid, that I would have to define this view data every time.

In terms of testability and what's ASP.NET MVC-ish how should I approach this?


Solution

  • Another option is to use the RenderAction method instead which will call an action (either on the current controller, or if you supply a controller name as well, that controller), which can then build the menu data for you, and call your ascx partial view:

    So on my master page I can have:

    <% Html.RenderAction("MenuArchiveList"); %>
    

    Then in my controller:

    public ActionResult MenuArchiveList() {
      return PartialView("BlogArchiveList",
                         _BlogRepository.GetArchiveYearPostCounts());
    }
    

    This then successfully finds the user control \Views\Shared\BlogArchiveList.ascx

    If you want to ensure that your action is only ever called in the context of a partial view, then you should decorate it with the ChildActionOnlyAttribute.

    This was added into System.Web.Mvc in version 2 from the "futures" namespace Microsoft.Web.Mvc.