2010-11-04 30 views
9

Khi bạn tạo một dự án MVC mới nó tạo ra một Site.Master với đánh dấu sau:ASP.net MVC - Navigation và làm nổi bật sự liên kết "hiện tại"

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

Tôi muốn đặt mã ở đây mà sẽ đánh dấu liên kết hiện tại nếu tôi ở trên trang đó.

Nếu tôi thêm liên kết khác như:

<li><%: Html.ActionLink("Products", "Index", "Products")%></li> 

tôi muốn liên kết sản phẩm để chủ động (sử dụng một lớp css như .active) nếu tôi về bất kỳ hành động trong bộ điều khiển sản phẩm.

Liên kết Giới thiệu phải hoạt động nếu tôi đang ở trên HomeController Giới thiệu về hành động. Liên kết Trang chủ nên hoạt động nếu tôi đang trên hành động Index của HomeController.

Cách tốt nhất để làm điều này trong MVC là gì?

Trả lời

23

Check-out this blog post

Nó cho thấy làm thế nào để tạo ra một mở rộng HTML mà bạn gọi thay vì thông thường Html.ActionLink Phần mở rộng sau đó gắn thêm class="selected" đến mục danh sách đó hiện đang hoạt động.

Sau đó bạn có thể đặt bất cứ điều gì định dạng/làm nổi bật mà bạn muốn trong CSS của bạn

EDIT

Chỉ cần thêm một số mã để thay vì chỉ một liên kết.

public static class HtmlHelpers 
{ 

    public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, 
             string linkText, 
             string actionName, 
             string controllerName 
             ) 
    { 

     string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action"); 
     string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller"); 

     if (actionName == currentAction && controllerName == currentController) 
     { 
      return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = "selected" }); 
     } 

     return htmlHelper.ActionLink(linkText, actionName, controllerName); 


    } 
} 

Bây giờ bạn cần phải xác định lớp selected của bạn trong CSS của bạn và sau đó trong quan điểm của bạn thêm một tuyên bố using ở đầu trang.

@using ProjectNamespace.HtmlHelpers

Và sử dụng MenuLink thay vì ActionLink

@Html.MenuLink("Your Menu Item", "Action", "Controller")

+0

điều này ngừng hoạt động khi bạn sử dụng RenderAction :( –

+2

Lưu ý: ActionLink thực sự là một phương pháp tiện ích mở rộng, đảm bảo bao gồm việc sử dụng System.Web.Mvc.Html; trong tệp mã của bạn, nếu không Visual Studio sẽ không thể tìm thấy nó. – Peter

+0

Sử dụng gói nuget gói «JetBrains.Annotations' để đánh dấu Bộ điều khiển và Hành động trong chế độ xem Dao cạo. '[AspMvcController]' và '[AspMvcAction]'. –

0

tôi sử dụng phương pháp này với một HtmlHelper cho vấn đề:

public static class HtmlHelpers 
{ 
    public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, 
              string linkText, 
              string actionName, 
              string controllerName 
             ) 
    { 

     string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action"); 
     string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller"); 

     if (actionName.Equals(currentAction, StringComparison.InvariantCultureIgnoreCase) && controllerName.Equals(currentController, StringComparison.InvariantCultureIgnoreCase)) 
     { 
      return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = "active" }); 
     } 

     return htmlHelper.ActionLink(linkText, actionName, controllerName); 

    } 
} 

và cho xem

@Html.MenuLink"Linktext", "action", "controller") 
0

Bạn có thể muốn kiểm tra hàng loạt của tôi về điều khiển chuyển hướng MVC, trong đó bao gồm khả năng tự động làm nổi bật các liên kết hiện tại:

http://mvcquicknav.apphb.com/

8

Bạn có thể làm điều này bằng cách sử dụng "đĩa dữ liệu" thuộc tính xác định các container (s) sau đó sử dụng jQuery lớp thay đổi CSS của liên kết, như sau:

<div class="..." data-navigation="true"> 
        <ul class="..."> 
         <li>@Html.ActionLink("About", "About", "Home")</li> 
         <li>@Html.ActionLink("Contact", "Contact", "Home")</li> 
        </ul> 
</div> 

<script> 
    $(function() { 
     $("div[data-navigation='true']").find("li").children("a").each(function() { 
      if ($(this).attr("href") === window.location.pathname) { 
       $(this).parent().addClass("active"); 
      } 
     }); 
    }); 
</script> 
+0

Cách dành cho danh sách thả xuống trong thanh điều hướng, có vẻ như không hoạt động cho điều đó – kirk

4

Dưới đây là một cách để thực hiện điều này như một helper MVC:

@helper NavigationLink(string linkText, string actionName, string controllerName) 
{ 
    if(ViewContext.RouteData.GetRequiredString("action").Equals(actionName, StringComparison.OrdinalIgnoreCase) && 
     ViewContext.RouteData.GetRequiredString("controller").Equals(controllerName, StringComparison.OrdinalIgnoreCase)) 
    { 
     <span>@linkText</span> 
    } 
    else 
    { 
     @Html.ActionLink(linkText, actionName, controllerName); 
    } 
} 

Sau đó nó có thể được sử dụng tương tự như sau:

@NavigationLink("Home", "index", "home") 
@NavigationLink("About Us", "about", "home") 

Một bài viết tốt về những người giúp đỡ MVC có thể được tìm thấy ở đây: http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

-1
<div class="navbar-collapse collapse"> 
      <ul class="nav navbar-nav"> 
       <li>@Html.ActionLink("Home", "Index", "Home")</li> 
       <li>@Html.ActionLink("About", "About", "Home")</li> 
       <li>@Html.ActionLink("Contact", "Contact", "Home")</li> 
       <li>@Html.ActionLink("Products", "Index", "Products")</li> 
       <li class="dropdown"> 
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Archivo<b class="caret"></b></a> 
        <ul class="dropdown-menu"> 
         <li>@Html.ActionLink("Document Type", "Index", "DocumentTypes")</li> 
         <li>@Html.ActionLink("Employee", "Index", "Employees")</li> 
         <li>@Html.ActionLink("Suppliers", "Index", "Suppliers")</li> 
        </ul> 
       </li>  
      </ul> 
      @Html.Partial("_LoginPartial") 
     </div> 
0

Nhờ @codingbadger cho các giải pháp.

Tôi đã nhận được các liên kết điều hướng được đánh dấu trên nhiều hành động vì vậy tôi quyết định thêm một vài tham số có chứa các cặp hành động điều khiển và nó sẽ đánh dấu liên kết nếu một trong các kết hợp đó được truy cập. Và, trong trường hợp của tôi, lớp nổi bật sẽ được áp dụng cho phần tử <li>.

Tôi đặt mã của tôi ở đây hy vọng nó sẽ giúp một người nào đó trong tương lai:

  • Dưới đây là phương pháp helper:

    /// <summary> 
    /// The link will be highlighted when it is used to redirect and also be highlighted when any action-controller pair is used specified in the otherActions parameter. 
    /// </summary> 
    /// <param name="selectedClass">The CSS class that will be applied to the selected link</param> 
    /// <param name="otherActions">A list of tuples containing pairs of Action Name and Controller Name respectively</param> 
    public static MvcHtmlString NavLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string parentElement, string selectedClass, IEnumerable<Tuple<string, string>> otherActions) 
    { 
        string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action"); 
        string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller"); 
    
        if ((actionName == currentAction && controllerName == currentController) || 
         (otherActions != null && otherActions.Any(pair => pair.Item1 == currentAction && pair.Item2 == currentController))) 
        { 
         return new MvcHtmlString($"<{parentElement} class=\"{selectedClass}\">{htmlHelper.ActionLink(linkText, actionName, controllerName)}</{parentElement}>"); 
        } 
    
        return new MvcHtmlString($"<{parentElement}>{htmlHelper.ActionLink(linkText, actionName, controllerName)}</{parentElement}>"); 
    } 
    
  • Và, đây là một ví dụ về cách sử dụng nó :

<ul> 
 
    @Html.NavLink("Check your eligibility", "CheckEligibility", "Eligibility", "li", "current-page", new Tuple<string, string>[] 
 
    { 
 
     new Tuple<string, string>("Index", "Eligibility"), 
 
     new Tuple<string, string>("RecheckEligibility", "Eligibility") 
 
    }) 
 
    @Html.NavLink("Apply for my loan", "Apply", "Loan", "li", "current-page") 
 
</ul>

Các vấn đề liên quan