views:

225

answers:

5

It's a simple question. How did stackoverflow do their menu in Asp.net MVC, with highlight on what page we are on.

+1  A: 

See for i.e. this URL

http://stackoverflow.com/questions this indicates that probably the Questions Controller handles this page. So it changes the View to display a highlighted menu item.

Henrik P. Hessel
That's the basic idea. I'm guessing there's some paging involved in the Linq to SQL models, among other things.
Robert Harvey
For sure :) Route Table i.e.
Henrik P. Hessel
+2  A: 

There is probably no MVC special magic that makes this happen.

I'm sure:

if( HttpContext.Current.Request.Path == "some some menu url" )

or

if( ViewContext_Or_ControllerContext.RouteData.Values["controller"] == "some value") 

is used someplace.

You could put this code in about three different locations ( View ( .aspx ), ViewModel, Custom HtmlHelper ) and they would all require that same bit of code.

jfar
This will be the basic. I will try to figure out the best way to make this DRY... :P
DucDigital
A: 

If you look at the page source, they've added a css class to the <li> element to change the background color. I'm guessing the code looks at what controller the user is accessing (questions, users, etc) and adds the class to that section's <li> tag.

Ken Pespisa
that's the basic for UI.
DucDigital
A: 

The NerdDinner tutorial covers paging here: http://nerddinnerbook.s3.amazonaws.com/Part8.htm

Robert Harvey
probably not paging, it's the menu
DucDigital
+1  A: 

For the purpose of this, i've writen some code down, there are some part that using my custom extension like Language, go ahead and use it, just ignore the minor part.

This one i place on top of my Partial that contain the menu to get the action and controller, so that i can pass this to the extension.

<%  string currentAction = ViewContext.RouteData.Values["action"].ToString();
    string currentController = ViewContext.RouteData.Values["controller"].ToString(); %>

This is the sidebar Item, basically this will generate a "li" tag with a link and your custom class to indicate whether the link is currently used in the page / highlight.

public static string SidebarItem(this System.Web.Mvc.HtmlHelper html, string currentAction, string currentController, string action, string controller, string languageKey, params object[] args)
{
    TagBuilder tb = new TagBuilder("li");
    if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) && string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
    {
        tb.GenerateId("activemenu");
    }
    string text = html.Language(languageKey, args);
    string link = html.ActionLink(text, action, controller).ToHtmlString();
    tb.SetInnerText("{0}");
    return String.Format(tb.ToString(), "<span>"+link+"</span>");
}

and here is the actual usage of the code above

<%= Html.SidebarItem(currentAction, currentController, "index", "home", "index") %>
DucDigital