ASP.NET MVC Partial Views and Data

Can someone explain why you are defining ViewData ["MenuData"] for each action for something like a dynamic menu?

I have a simple partial view that displays a menu, I present this menu on the main page. This is intuitive for me, based on ASP.NET WebForms, but the only way to populate the menu is to pass ViewData ["MenuData"], but then I have to do this in every controller action. It seems to me that it’s a little silly that I will have to determine the data of this kind every time.

In terms of verifiability and the fact that ASP.NET is MVC-ish, how should I approach this?

+5
source share
2 answers

Another option is to use a method RenderActionthat will trigger an action (either on the current controller or on delivery the name of the controller, as well as this controller), which can then create menu data for you and invoke a partial ascx view:

So, on my main page, I can:

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

Then in my controller:

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

Then successfully finds user control \Views\Shared\BlogArchiveList.ascx

If you want your action to be invoked only in the context of a partial view, you should decorate it with ChildActionOnlyAttribute.

This was added to System.Web.Mvc in version 2 of the Microsoft.Web.Mvc Futures namespace.

+4
source

, , .

. ViewModel

0

All Articles