Jak wizualnie wskazać bieżącą stronę w ASP.NET MVC?

Jako podstawa do dyskusji. Stwórz standard ASP.NET MVC Web project.

Będzie zawierać dwie pozycje menu na stronie wzorcowej:

<div id="menucontainer">
  <ul id="menu">
    <li>
      <%= Html.ActionLink("Home", "Index", "Home")%></li>
    <li>
      <%= Html.ActionLink("About", "About", "Home")%></li>
  </ul>
</div>

Jak mogę ustawić wizualny styl CSS wskazujący bieżącą stronę. Na przykład, gdy w About page / controller, zasadniczo chciałbym to zrobić:

<%= Html.ActionLink("About", "About", "Home", new {class="current"})%></li>

I oczywiście, gdy na stronie głównej:

<%= Html.ActionLink("Home", "Index", "Home", new {class="current"})%></li>

(posiadanie nazwy stylu CSS current, która wizualnie wskazuje w menu, że jest to bieżący strona.)

Mógłbym wydzielić div menu ze strony wzorcowej na uchwyt miejsca treści, ale oznaczałoby to, że muszę umieścić menu na każdej stronie.

Jakieś pomysły, czy jest na to jakieś dobre rozwiązanie?
Author: Leniel Maccaferri, 2009-09-24

5 answers

Najprostszym sposobem jest pobranie bieżącego kontrolera i akcji z RouteData ViewContext. Zwróć uwagę na zmianę podpisu i użycie @ do ucieczki słowa kluczowego.

<% var controller = ViewContext.RouteData.Values["controller"] as string ?? "Home";
   var action = ViewContext.RouteData.Values["action"] as string ?? "Index";
   var page = (controller + ":" + action).ToLower();
 %>

<%= Html.ActionLink( "About", "About", "Home", null,
                     new { @class = page == "home:about" ? "current" : "" ) %>
<%= Html.ActionLink( "Home", "Index", "Home", null,
                     new { @class = page == "home:index" ? "current" : "" ) %>

Zauważ, że możesz połączyć to rozszerzenie HtmlHelper jak @ Jon ' s i uczynić je czystszym.

<%= Html.MenuLink( "About", "About", "Home", null, null, "current" ) %>

Gdzie MenuActionLink jest

public static class MenuHelperExtensions
{
     public static string MenuLink( this HtmlHelper helper,
                                    string text,
                                    string action,
                                    string controller,
                                    object routeValues,
                                    object htmlAttributes,
                                    string currentClass )
     {
         RouteValueDictionary attributes = new RouteValueDictionary( htmlAttributes );
         string currentController = helper.ViewContext.RouteData.Values["controller"] as string ?? "home";
         string currentAction = helper.ViewContext.RouteData.Values["action"] as string ?? "index";
         string page = string.Format( "{0}:{1}", currentController, currentAction ).ToLower();
         string thisPage = string.Format( "{0}:{1}", controller, action ).ToLower();
         attributes["class"] = (page == thisPage) ? currentClass : "";
        return helper.ActionLink( text, action, controller, new RouteValueDictionary( routeValues ), attributes );
     }
}
 24
Author: tvanfosson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-24 15:25:23

Niedawno stworzyłem do tego Helpera HTML, który wygląda następująco:

public static string NavigationLink(this HtmlHelper helper, string path, string text)
{
    string cssClass = String.Empty;
    if (HttpContext.Current.Request.Path.IndexOf(path) != -1)
    {
        cssClass = "class = 'selected'";
    }

    return String.Format(@"<li><a href='{0}' {1}>{2}</a></li>", path, cssClass, text);
}

Implementacja wygląda tak:

  <ul id="Navigation">
  <%=Html.NavigationLink("/Path1", "Text1")%>
  <%=Html.NavigationLink("/Path2", "Text2")%>
  <%=Html.NavigationLink("/Path3", "Text3")%>
  <%=Html.NavigationLink("/Path4", "Text4")%>
  </ul>
 1
Author: Jon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-24 13:50:59

Jeśli używasz T4MVC, możesz użyć tego:

        public static HtmlString MenuLink(
        this HtmlHelper helper,
        string text,
        IT4MVCActionResult action,
        object htmlAttributes = null)
    {
        var currentController = helper.ViewContext.RouteData.Values["controller"] as string ?? "home";
        var currentAction = helper.ViewContext.RouteData.Values["action"] as string ?? "index";

        var attributes = new RouteValueDictionary(htmlAttributes);
        var cssClass = (attributes.ContainsKey("class"))
                           ? attributes["class"] + " "
                           : string.Empty;

        string selectedClass;
        if(action.Controller.Equals(currentController, StringComparison.InvariantCultureIgnoreCase)
        {
            selectedClass = "selected-parent";
            if(action.Action.Equals(currentAction, StringComparison.InvariantCultureIgnoreCase))
                selectedClass = "selected";
        }
        cssClass += selectedClass;

        attributes["class"] = cssClass;

        return helper.ActionLink(text, (ActionResult)action, attributes);
    }
 1
Author: Jason Wicker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-29 18:06:17

Może być tak, że jest to piąty parametr, więc umieść null przed atrybutem html. Ten post tutaj opisuje to jako takie, choć można przekazać w niektórych rzeczy na 4th arguement, 5th jest specjalnie dla HTMLattributes

 0
Author: Amadiere,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-24 13:52:35
<script type="javascript/text">
$( document ).ready( function() {

        @if (Request.Url.AbsolutePath.ToLower() == "/") 
        {
            @Html.Raw("$('.navbar-nav li').eq(0).attr('class','active');")
        }

        @if (Request.Url.AbsolutePath.ToLower().Contains("details")) 
        {
            @Html.Raw("$('.navbar-nav li').eq(1).attr('class','active');")
        }

        @if (Request.Url.AbsolutePath.ToLower().Contains("schedule")) 
        {
            @Html.Raw("$('.navbar-nav li').eq(2).attr('class','active');")
        }

    });
</script>

Wrzuciłem to razem w 5 minut, prawdopodobnie mógłbym go refaktorować, ale powinien dać ci podstawową ideę, prawdopodobnie najbardziej przydatną dla mniejszych witryn.

 0
Author: Netferret,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-12 17:01:58