In ASP.NET MVC 2 - How do I get Route Values into my navigation controller so I can highlight the current link?

被刻印的时光 ゝ 提交于 2019-11-30 23:54:38

You don't need to pass route data to a controller because the controller already has knowledge of it via the RouteData property:

public ActionResult Index() {
    // You could use this.RouteData here
    ...
}

Now if you want to pass some simple arguments like current action that was used to render the view you could do this:

<%= Html.RenderAction(
    "MenuOfStreamEntries",
    "Nav",
    new {
        currentStreamUrl = "Blog", 
        currentAction = ViewContext.RouteData.Values["action"],
        currentController = ViewContext.RouteData.Values["controller"]
    }
); %>

And in your controller:

public ActionResult Nav(string currentAction, string currentController) 
{
    ...
}

Taken from this good article.

Create a custom extension method:

public static class HtmlExtensions
{
    public static MvcHtmlString ActionMenuItem(this HtmlHelper htmlHelper, String linkText,
        String actionName, String controllerName)
    {
        var tag = new TagBuilder("li");

        if ( htmlHelper.ViewContext.RequestContext
            .IsCurrentRoute(null, controllerName, actionName) )
        {
            tag.AddCssClass("selected");
        }

        tag.InnerHtml = htmlHelper.ActionLink(linkText, actionName, controllerName).ToString();

        return MvcHtmlString.Create(tag.ToString());
    }
}

Your HTML markup:

<div id="menucontainer">

    <ul id="menu">
        <%= Html.ActionMenuItem("Home", "Index", "Home") %>
        <%= Html.ActionMenuItem("About", "About", "Home") %>
    </ul>

</div>

Produces the following output:

<div id="menucontainer">

    <ul id="menu">
        <li class="selected"><a href="/">Home</a></li>
        <li><a href="/Home/About">About</a></li>
    </ul>

</div>
Josh

Here's a sample method we wrote for doing something similar.

public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName)
{
  string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
  string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];

  return currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!