当您创建一个新的 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 - 导航和突出显示“当前";关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!