select right menu on master page in MVC from child page

前端 未结 2 1979
闹比i
闹比i 2020-12-18 09:53

I have a couple of list items in a shared _layout.cshtm file (master page) in my MVC application.

something like:

相关标签:
2条回答
  • 2020-12-18 10:34

    Just wanted to share what i do:

    I create folder App_Code and add CustomHelpers.cshtml. In it i create something like this:

    @helper MainMenu(string SelectedItem) {
        <ul class="MainMenu">
            <li><a href="/home" @if (SelectedItem == "Home") { <text>class="Active"</text> }>Home</a></li>
            <li><a href="/about" @if (SelectedItem == "About") { <text>class="Active"</text> }>About</a></li>
            <li><a href="/foo" @if (SelectedItem == "Foo") { <text>class="Active"</text> }>Foo</a></li>
        </ul>
    }
    

    Than in my MasterPage (_Layout.cshtml) i add this where i want my menu to apear:

    @CustomHelpers.MainMenu(ViewBag.SelectedMenu)
    

    And than in my view, just like i change my page title, i change my selected menu:

    @{
        ViewBag.Title = "Welcome to my homepage";
        ViewBag.SelectedMenu = "Home";
    }
    

    Got my idea from this tutorial: www.asp.net/mvc/videos/mvc-3/mvc-3-razor-helpers

    0 讨论(0)
  • 2020-12-18 10:48

    You could write a custom helper method:

    public static MvcHtmlString MenuItem(
        this HtmlHelper htmlHelper, 
        string text,
        string action, 
        string controller
    )
    {
        var li = new TagBuilder("li");
        var routeData = htmlHelper.ViewContext.RouteData;
        var currentAction = routeData.GetRequiredString("action");
        var currentController = routeData.GetRequiredString("controller");
        if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
            string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
        {
            li.AddCssClass("selected");
        }
        li.SetInnerText(text);
        return MvcHtmlString.Create(li.ToString());
    }
    

    and then:

    <ul>
        @Html.MenuItem("Home", "home", "home")
        @Html.MenuItem("About", "about", "home")
        @Html.MenuItem("Contact", "contact", "home")
        @Html.MenuItem("Blog", "blog", "home")
    </ul>
    

    The helper check the current action and controller and if they match the one passed as arguments to the helper it appends the selected CSS class to the li.

    0 讨论(0)
提交回复
热议问题