17

議論のベースとして。標準の ASP.NET MVC Web プロジェクトを作成します。

マスター ページには 2 つのメニュー項目が含まれます。

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

現在のページを示す視覚的な CSS スタイルを設定するにはどうすればよいですか。たとえば、Aboutページ/コントローラーでは、基本的にこれを行いたいと思います:

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

そしてもちろん、ホームページ上では:

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

(これが現在のページであることをメニューで視覚的に示す CSS スタイル名を current にする。)

メニュー div をマスター ページからコンテンツ プレース ホルダーに分割することもできますが、それは、すべてのページにメニューを配置する必要があることを意味します。

これに対する良い解決策はありますか?

4

5 に答える 5

24

最も簡単な方法は、ViewContext の RouteData から現在のコントローラーとアクションを取得することです。署名の変更と、キーワードをエスケープするための @ の使用に注意してください。

<% 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" : "" ) %>

これを @Jon のような HtmlHelper 拡張と組み合わせて、よりクリーンにすることができることに注意してください。

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

MenuActionLink の場所

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 );
     }
}
于 2009-09-24T12:35:49.960 に答える
1

最近、次のようなHTMLヘルパーを作成しました。

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);
}

実装は次のようになります。

  <ul id="Navigation">
  <%=Html.NavigationLink("/Path1", "Text1")%>
  <%=Html.NavigationLink("/Path2", "Text2")%>
  <%=Html.NavigationLink("/Path3", "Text3")%>
  <%=Html.NavigationLink("/Path4", "Text4")%>
  </ul>
于 2009-09-24T13:50:59.123 に答える
1

T4MVC を使用している場合は、これを使用できます。

        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);
    }
于 2011-06-29T18:06:17.063 に答える
0

5 番目のパラメーターである可能性があるため、html 属性の前に null を挿入します。この投稿では、4 番目の引数でいくつかのものを渡すことができますが、5 番目の引数は特に HTML 属性用です。

于 2009-09-24T12:35:29.977 に答える
0
<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>

これを 5 分でまとめました。おそらくリファクタリングできますが、基本的なアイデアを提供する必要があります。これはおそらく小規模なサイトに最も役立つでしょう。

于 2014-03-12T17:01:58.703 に答える