Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

asp.net mvc - select right menu on master page in MVC from child page

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

something like:

<ul>
    <li>Home</li>
    <li>about</li>
    <li>contact</li>
    <li>blog</li>
</ul>

when the user is in a homepage, I want home li item to have class selected, like so:

<li class="selected">Home</li>

and so on. What is the best way to do this?

In regular asp.net website, I used to have a method in master page and call that method from child page but in MVC I am not sure what to do.

thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...