問題描述
當您創建一個新的 MVC 項目時,它會創建一個帶有以下標記的 Site.master:
When you create a new MVC project it creates a Site.master with the following markup:
<div id="menucontainer">
<ul id="menu">
<li><%: Html.ActionLink("Home", "Index", "Home")%></li>
<li><%: Html.ActionLink("About", "About", "Home")%></li>
</ul>
</div>
如果我在該頁面上,我想在此處放置代碼以突出顯示當前鏈接.
I would like to put code in here that will highlight the current link if I am on that page.
如果我添加另一個鏈接,例如:
If I add another link such as:
<li><%: Html.ActionLink("Products", "Index", "Products")%></li>
如果我在 Products 控制器中執行任何操作,我希望 Products 鏈接處于活動狀態(使用 .active 之類的 css 類).
I would want the Products link to be active (using a css class like .active) if I'm on any action in the Products controller.
如果我在 HomeController About 操作中,About 鏈接應該處于活動狀態.如果我在 HomeController 的 Index 操作中,Home 鏈接應該是活動的.
The About link should be active if I'm on the HomeController About action. The Home link should be active if I'm on the Index action of the HomeController.
在 MVC 中執行此操作的最佳方法是什么?
What is the best way to do this in MVC?
推薦答案
查看這篇博文
它展示了如何創建一個您調用的 HTML 擴展,而不是通常的 Html.ActionLink
該擴展然后將 class="selected"
附加到列表項目前處于活動狀態.
It shows how to create an HTML Extension that you call instead of the usual Html.ActionLink
The extension then appends class="selected"
to the list item that is currently active.
然后,您可以在 CSS 中添加任何您想要的格式/突出顯示
You can then put whatever formatting/highlighting you want in your CSS
編輯
只是添加一些代碼而不僅僅是一個鏈接.
Just adding some code to rather than just a link.
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);
}
}
現在你需要在你的 CSS 中定義你的 selected
類,然后在你的視圖中在頂部添加一個 using
語句.
Now you need to define your selected
class in your CSS and then in your views add a using
statement at the top.
@using ProjectNamespace.HtmlHelpers
并使用 MenuLink
代替 ActionLink
@Html.MenuLink("Your Menu Item", "Action", "Controller")
這篇關于ASP.net MVC - 導航和突出顯示“當前";關聯的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!