問題描述
當(dāng)您創(chuàng)建一個(gè)新的 MVC 項(xiàng)目時(shí),它會(huì)創(chuàng)建一個(gè)帶有以下標(biāo)記的 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>
如果我在該頁(yè)面上,我想在此處放置代碼以突出顯示當(dāng)前鏈接.
I would like to put code in here that will highlight the current link if I am on that page.
如果我添加另一個(gè)鏈接,例如:
If I add another link such as:
<li><%: Html.ActionLink("Products", "Index", "Products")%></li>
如果我在 Products 控制器中執(zhí)行任何操作,我希望 Products 鏈接處于活動(dòng)狀態(tài)(使用 .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 鏈接應(yīng)該處于活動(dòng)狀態(tài).如果我在 HomeController 的 Index 操作中,Home 鏈接應(yīng)該是活動(dòng)的.
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 中執(zhí)行此操作的最佳方法是什么?
What is the best way to do this in MVC?
推薦答案
查看這篇博文
它展示了如何創(chuàng)建一個(gè)您調(diào)用的 HTML 擴(kuò)展,而不是通常的 Html.ActionLink
該擴(kuò)展然后將 class="selected"
附加到列表項(xiàng)目前處于活動(dòng)狀態(tài).
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
編輯
只是添加一些代碼而不僅僅是一個(gè)鏈接.
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);
}
}
現(xiàn)在你需要在你的 CSS 中定義你的 selected
類,然后在你的視圖中在頂部添加一個(gè) using
語(yǔ)句.
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")
這篇關(guān)于ASP.net MVC - 導(dǎo)航和突出顯示“當(dāng)前";關(guān)聯(lián)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!