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?
Another option is to use the
RenderActionmethod 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:
Then in my controller:
This then successfully finds the user control
\Views\Shared\BlogArchiveList.ascxIf 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.