views:

42

answers:

2

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?

A: 

You should use a base controller which handles the repeated population of your view model and then have all your controllers derive from it

see here http://stackoverflow.com/questions/664205/viewmodel-best-practices/683648#683648

Mark
+1  A: 

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.

Zhaph - Ben Duguid
That's the stuff. Thank you.
John Leidegren
No problem, it's a pleasure.
Zhaph - Ben Duguid

related questions