我试图在MVC中添加一个“活动”类到我的引导导航栏中,但是下面的代码并没有显示活动类:
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home", null, new {@class="active"})</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
这将解析为一个看起来格式正确的类,但不起作用:
<a class="active" href="/">Home</a>
在Bootstrap文档中,它指出'a‘标签不应该在导航栏中使用,但上面是我认为向Html.ActionLink添加类的正确方式。有没有其他(整洁的)方法可以做到这一点?
发布于 2015-04-30 21:08:42
扩展名:
public static MvcHtmlString LiActionLink(this HtmlHelper html, string text, string action, string controller)
{
var context = html.ViewContext;
if (context.Controller.ControllerContext.IsChildAction)
context = html.ViewContext.ParentActionViewContext;
var routeValues = context.RouteData.Values;
var currentAction = routeValues["action"].ToString();
var currentController = routeValues["controller"].ToString();
var str = String.Format("<li role=\"presentation\"{0}>{1}</li>",
currentAction.Equals(action, StringComparison.InvariantCulture) &&
currentController.Equals(controller, StringComparison.InvariantCulture) ?
" class=\"active\"" :
String.Empty, html.ActionLink(text, action, controller).ToHtmlString()
);
return new MvcHtmlString(str);
}
用法:
<ul class="nav navbar-nav">
@Html.LiActionLink("About", "About", "Home")
@Html.LiActionLink("Contact", "Contact", "Home")
</ul>
发布于 2016-01-22 18:39:16
我通过在asp.net mvc中添加一个view bag参数来做到这一点。我都做了些什么
在每个页面中添加ViewBag.Current = "Scheduler";
like参数
在布局页面中
<ul class="nav navbar-nav">
<li class="@(ViewBag.Current == "Scheduler" ? "active" : "") "><a href="@Url.Action("Index","Scheduler")" target="_self">Scheduler</a></li>
</ul>
这解决了我的问题。
发布于 2016-10-26 14:43:30
可能有点晚了。但希望这能有所帮助。
public static class Utilities
{
public static string IsActive(this HtmlHelper html,
string control,
string action)
{
var routeData = html.ViewContext.RouteData;
var routeAction = (string)routeData.Values["action"];
var routeControl = (string)routeData.Values["controller"];
// both must match
var returnActive = control == routeControl &&
action == routeAction;
return returnActive ? "active" : "";
}
}
使用方法如下:
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class='@Html.IsActive("Home", "Index")'>
@Html.ActionLink("Home", "Index", "Home")
</li>
<li class='@Html.IsActive("Home", "About")'>
@Html.ActionLink("About", "About", "Home")
</li>
<li class='@Html.IsActive("Home", "Contact")'>
@Html.ActionLink("Contact", "Contact", "Home")
</li>
</ul>
</div>
从http://www.codingeverything.com/2014/05/mvcbootstrapactivenavbar.html获得推荐人
https://stackoverflow.com/questions/20410623
复制相似问题