For rendering my menu in MVC 3 Razor I have in the Home controller a Menu action: public ActionResult Menu() {...} This action gets the menu items and render them using a view. In the _Layout I use: @Html.Action("Menu", "Home") for rendering the menu. This works fine.
My problem is that I want to select the curren开发者_JS百科t item. For this each action that render an item that is in the menu will add to the ViewBag the selected menu item. The problem is that the ViewBag is empty in the Menu action. Is this the correct approach? I want to render a menu using a controller + view not only a view. I want this in order to avoid having logic code in the view code and to be able to test it.
Do you know a better approach?
How can I pass data from _Layout.cshtml to an action that I render using @html.Action?
You could pass it as parameter:
@Html.Action("Menu", "Home", new { sleectedItem = (string)ViewBag.SomeItem })
and then in the child controller action use this:
public ActionResult Menu(string selectedItem)
{
...
}
or if all you need is to fetch the current controller and action you could simply fetch this information from the RouteData and get rid of any ViewBag:
public ActionResult Menu()
{
var rd = ControllerContext.ParentActionViewContext.RouteData;
var action = rd.GetRequiredString("action");
var controller = rd.GetRequiredString("controller");
// Now that you know the action and the controller build up your view model
// and pass to the view. It will then know which menu item to preselect
...
}
Try looking at the RouteData
from inside an action method or the ViewContext
if inside an HtmlHelper
extension when constructing your menu. Pull out which is the current controller and which is the current action and set that menu item accordingly.
From an action method:
object controller = RouteData.Values["controller"];
object action = RouteData.Values["action"];
object area = RouteData.DataTokens["area"];
From an html helper:
object controller = helper.ViewContext.RouteData.Values["controller"];
object action = helper.ViewContext.RouteData.Values["action"];
object area = helper.ViewContext.RouteData.DataTokens["area"];
Here is a helper I wrote a while back to print a css class to an active menu: http://blog.tomasjansson.com/2010/09/asp-net-mvc-helper-for-active-tab-in-tab-menu/
精彩评论