如何加上「;主动的;在ASP.NET MVC中初始化为Html.ActionLink
我试图在MVC中向我的引导导航栏添加一个“活动”类,但以下内容在这样编写时没有显示活动类:如何加上「;主动的;在ASP.NET MVC中初始化为Html.ActionLink,asp.net,css,asp.net-mvc,twitter-bootstrap,Asp.net,Css,Asp.net Mvc,Twitter Bootstrap,我试图在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&g
<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>
<ul class="nav navbar-nav">
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@HtmlHelpers.MenuItem("Default", "Home")
public ActionResult Index()
{
ViewBag.Title = "Home";
ViewBag.Home = "class = active";
return View();
}
<li @ViewBag.Home>@Html.ActionLink("Home", "Index", "Home", null, new { title = "Go home" })</li>
- @ActionLink(“Home”、“Index”、“Home”、null、new{@class=“active”})
- @ActionLink(“关于”、“关于”、“主页”)
- @ActionLink(“联系人”、“联系人”、“主页”)
这将解析为看起来格式正确的类,但不起作用:
<a class="active" href="/">Home</a>
在Bootstrap文档中,它声明不应在navbar中使用“a”标记,但我认为以上是将类添加到Html.ActionLink的正确方法。有没有其他(整洁的)方法可以做到这一点 如果它根本不显示,原因是您需要两个@符号:
@@class
但是,我相信您可能需要将活动类放在“li”标记上,而不是放在“a”标记上。根据bootstrap文档():
因此,您的代码将是:
<ul class="nav navbar-nav">
<li class="active">@Html.ActionLink("Home", "Index", "Home", null)</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
- @Html.ActionLink(“Home”、“Index”、“Home”、null)
- @ActionLink(“关于”、“关于”、“主页”)
- @ActionLink(“联系人”、“联系人”、“主页”)
在引导过程中,活动的类需要应用于
元素,而不是
基于活动与否处理UI样式的方式与ASP.NET MVC的ActionLink
helper无关。这是遵循引导框架构建方式的正确解决方案
<ul class="nav navbar-nav">
<li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
它的代码并不漂亮,但它可以完成任务,如果您愿意,还可以将菜单提取到局部视图中。有很多方法可以更干净地做到这一点,但既然你才刚刚开始,我就到此为止。祝你学习ASP.NET MVC好运
后期编辑:
public static string IsSelected(this IHtmlHelper htmlHelper, string controllers, string actions, string cssClass = "selected")
{
string currentAction = htmlHelper.ViewContext.RouteData.Values["action"] as string;
string currentController = htmlHelper.ViewContext.RouteData.Values["controller"] as string;
IEnumerable<string> acceptedActions = (actions ?? currentAction).Split(',');
IEnumerable<string> acceptedControllers = (controllers ?? currentController).Split(',');
return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
cssClass : String.Empty;
}
<li><a @RouterLink("Index","Home")>Home</a></li>
这个问题似乎有点流量,所以我想我应该使用HtmlHelper
扩展提供一个更优雅的解决方案
编辑03-24-2015:必须重写此方法,以允许多个操作和控制器触发所选行为,以及从子操作部分视图调用此方法时的处理,我想我会共享此更新
public static string IsSelected(this HtmlHelper html, string controllers = "", string actions = "", string cssClass = "selected")
{
ViewContext viewContext = html.ViewContext;
bool isChildAction = viewContext.Controller.ControllerContext.IsChildAction;
if (isChildAction)
viewContext = html.ViewContext.ParentActionViewContext;
RouteValueDictionary routeValues = viewContext.RouteData.Values;
string currentAction = routeValues["action"].ToString();
string currentController = routeValues["controller"].ToString();
if (String.IsNullOrEmpty(actions))
actions = currentAction;
if (String.IsNullOrEmpty(controllers))
controllers = currentController;
string[] acceptedActions = actions.Trim().Split(',').Distinct().ToArray();
string[] acceptedControllers = controllers.Trim().Split(',').Distinct().ToArray();
return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
cssClass : String.Empty;
}
与.NET内核配合使用:
public static string IsSelected(this IHtmlHelper htmlHelper, string controllers, string actions, string cssClass = "selected")
{
string currentAction = htmlHelper.ViewContext.RouteData.Values["action"] as string;
string currentController = htmlHelper.ViewContext.RouteData.Values["controller"] as string;
IEnumerable<string> acceptedActions = (actions ?? currentAction).Split(',');
IEnumerable<string> acceptedControllers = (controllers ?? currentController).Split(',');
return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
cssClass : String.Empty;
}
<li><a @RouterLink("Index","Home")>Home</a></li>
选择公共静态字符串(此IHtmlHelper htmlHelper、字符串控制器、字符串操作、字符串cssClass=“已选择”)
{
字符串currentAction=htmlHelper.ViewContext.RoutedData.Values[“action”]作为字符串;
字符串currentController=htmlHelper.ViewContext.RoutedData.Values[“controller”]作为字符串;
IEnumerable acceptedActions=(actions??currentAction).Split(',');
IEnumerable AcceptedController=(控制器??currentController).Split(',');
返回acceptedActions.Contains(currentAction)和&AcceptedController.Contains(currentController)?
cssClass:String.Empty;
}
示例用法:
<ul>
<li class="@Html.IsSelected(actions: "Home", controllers: "Default")">
<a href="@Url.Action("Home", "Default")">Home</a>
</li>
<li class="@Html.IsSelected(actions: "List,Detail", controllers: "Default")">
<a href="@Url.Action("List", "Default")">List</a>
</li>
</ul>
-
-
由@dombenoit给出的答案是有效的。尽管它引入了一些需要维护的代码。请检查以下语法:
using (var nav = Html.Bootstrap().Begin(new Nav().Style(NavType.NavBar).SetLinksActiveByControllerAndAction()))
{
@nav.ActionLink("Link 1", "action1")
@nav.ActionLink("Link 2", "action2")
@nav.Link("External Link", "#")
}
请注意.SetLinksActiveByControllerAndAction()方法的使用
如果您想知道是什么使这种语法成为可能,请查看添加“.ToString”以改进ASP.NET MVC上的比较
<ul class="nav navbar-nav">
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>
- @Html.ActionLink(“Home”、“Index”、“Home”)
- @Html.ActionLink(“About”、“About”、“Home”)
- @Html.ActionLink(“Contact”、“Contact”、“Home”)
--扩展:
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);
}
public static MvcHtmlString LiActionLink(此HtmlHelper html、字符串文本、字符串操作、字符串控制器)
{
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(“{1} ”,
currentAction.Equals(action、StringComparison.InvariantCulture)&&
currentController.Equals(控制器、StringComparison.InvariantCulture)?
“类=\“活动\”:
String.Empty、html.ActionLink(文本、操作、控制器).ToHtmlString()
);
返回新的MvcHtmlString(str);
}
用法:
<ul class="nav navbar-nav">
@Html.LiActionLink("About", "About", "Home")
@Html.LiActionLink("Contact", "Contact", "Home")
</ul>
<li active-when="/Home/Index">
@LiActionLink(“关于”、“关于”、“主页”)
@LiActionLink(“联系人”、“联系人”、“主页”)
我们还可以从RequestContext创建UrlHelper
,我们可以从MvcHandler本身获得它。因此,我相信,如果有人想保持这种逻辑,那么以下方法会有所帮助:
在项目根目录中创建名为AppCode
的文件夹李>
在那里创建一个名为HtmlHelpers.cshtml的文件
在其中创建辅助对象:
@helper MenuItem(string action, string controller)
{
var mvcHandler = Context.CurrentHandler as MvcHandler;
if (mvcHandler != null)
{
var url = new UrlHelper(mvcHandler.RequestContext);
var routeData = mvcHandler.RequestContext.RouteData;
var currentAction = routeData.Values["action"].ToString();
var currentController = routeData.Values["controller"].ToString();
var isCurrent = string.Equals(currentAction, action, StringComparison.InvariantCultureIgnoreCase) &&
string.Equals(currentController, controller, StringComparison.InvariantCultureIgnoreCase);
<div class="@(isCurrent ? "active" : "")">
<div>@url.Action(action, controller)</div>
</div>
}
}
希望它对某人有所帮助。我通过在asp.net mvc中添加一个视图包参数成功地做到了这一点。我做了什么
添加了ViewBag.Current=“调度器”代码>每个页面中的like参数
在布局页面中
<ul class="nav navbar-nav">
<li class="@(ViewBag.Current == "Scheduler" ? "active" : "") "><a href="@Url.Action("Index","Scheduler")" target="_self">Scheduler</a></li>
</ul>
这就解决了我的问题。我也在寻找解决方案,jQuery帮了大忙。F
{ string controller = ViewContext.RouteData.Values["Controller"].ToString();
string action = ViewContext.RouteData.Values["Action"].ToString();}
<ul class="nav navbar-nav">
<li class="@((controller == "Home" && action == "Index") ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
<li class="@((controller == "Home" && action == "About") ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
<li class="@((controller == "Home" && action == "Contact") ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
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>
<script type="text/javascript">
$(document).ready(function () {
$('li.active active-menu').removeClass('active active-menu');
$('a[href="/MgtCustomer/Index"]').closest('li').addClass('active active-menu');
});
</script>
@{
string controllerAction = ViewContext.RouteData.Values["Controller"].ToString() + ViewContext.RouteData.Values["Action"].ToString();
}
<ul class="nav navbar-nav">
<li class="@(controllerAction == "HomeIndex" ? "active" : "" )">@Html.ActionLink("Home", "Index", "Home")</li>
<li class="@(controllerAction == "AboutIndex" ? "active" : "" )">@Html.ActionLink("About", "Index", "About")</li>
<li class="@(controllerAction == "HomeContact" ? "active" : "" )">@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@{
string controllerAction = ViewContext.RouteData.Values["Controller"].ToString() + ViewContext.RouteData.Values["Action"].ToString();
Func<string, string> IsSelected= x => x==controllerAction ? "active" : "";
}
@Html.ActionLink("Inicio", "Index", "Home", new { area = "" }, new { @class = IsSelected("HomeIndex")})
-Install-Package Betalgo.MvcMenuNavigator
public enum HeaderTop
{
Dashboard,
Product
}
public enum HeaderSub
{
Index
}
[MenuNavigator(HeaderTop.Product, HeaderSub.Index)]
public class ProductsController : Controller
{
public async Task<ActionResult> Index()
{
return View();
}
[MenuNavigator(HeaderTop.Dashboard, HeaderSub.Index)]
public async Task<ActionResult> Dashboard()
{
return View();
}
}
@{
var headerTop = (HeaderTop?)MenuNavigatorPageDataNavigatorPageData.HeaderTop;
var headerSub = (HeaderSub?)MenuNavigatorPageDataNavigatorPageData.HeaderSub;
}
<div class="nav-collapse collapse navbar-collapse navbar-responsive-collapse">
<ul class="nav navbar-nav">
<li class="@(headerTop==HeaderTop.Dashboard?"active selected open":"")">
<a href="@Url.Action("Index","Home")">Dashboard</a>
</li>
<li class="@(headerTop==HeaderTop.Product?"active selected open":"")">
<a href="@Url.Action("Index", "Products")">Products</a>
</li>
</ul>
public static string IsLinkActive(this UrlHelper url, string action, string controller)
{
if (url.RequestContext.RouteData.Values["controller"].ToString() == controller &&
url.RequestContext.RouteData.Values["action"].ToString() == action)
{
return "active";
}
return "";
}
<li class="@(Context.Request.Path.Value.ToLower().Contains("about") ? "active " : "" ) nav-item">
<a class="nav-link" asp-area="" asp-controller="Home" asp-action="About">About</a>
</li>
<li class="has-sub @(ViewBag.Title == "Dashboard 1" || ViewBag.Title == "Dashboard 2" ? "active" : "" )">
<a href="javascript:;">
<b class="caret"></b>
<i class="fa fa-th-large"></i>
<span>Dashboard</span>
</a>
<ul class="sub-menu">
<li class="@(ViewBag.Title == "Dashboard 1" ? "active" : "")"><a href="index.html">Dashboard v1</a></li>
<li class="@(ViewBag.Title == "Dashboard 2" ? "active" : "")"><a href="index_v2.html">Dashboard v2</a></li>
</ul>
</li>
<ul class="navbar-nav mr-auto">
<li class="nav-item @Html.IfSelected("Index")">
<a class="nav-link" href="@Url.Action("Index", "Home")">Home</a>
</li>
<li class="nav-item @Html.IfSelected("Controls")">
<a class="nav-link" href="@Url.Action("Controls", "Home")">MVC Controls</a>
</li>
<li class="nav-item @Html.IfSelected("About")">
<a class="nav-link" href="@Url.Action("About", "Home")">About</a>
</li>
</ul>
public static string IfSelected(this HtmlHelper html, string action)
{
return html
.ViewContext
.RouteData
.Values["action"]
.ToString() == action
? " active"
: "";
}
public static class LinkExtensions
{
public static MvcHtmlString ActiveActionLink(this HtmlHelper html, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
{
return ActiveActionLink(html, linkText, actionName, controllerName, new RouteValueDictionary(routeValues), HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString ActiveActionLink(this HtmlHelper html, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)
{
const string activeClassName = "active";
var routeData = html.ViewContext.RouteData;
var routeAction = (string)routeData.Values["action"];
var routeController = (string)routeData.Values["controller"];
var active = controllerName.Equals(routeController) && actionName.Equals(routeAction);
if (active)
{
var @class = (string)htmlAttributes["class"];
htmlAttributes["class"] = string.IsNullOrEmpty(@class)
? activeClassName
: @class + " active";
}
var link = html.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);
return link;
}
}
@Html.ActiveActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-item nav-link" })
@helper RouterLink(string action, string controller)
{
var IsActive = ViewContext.RouteData.Values["Controller"].ToString() == controller && ViewContext.RouteData.Values["Action"].ToString() == action;
<text>href="@Url.Action(action, controller)"</text>if (IsActive){ <text>class="active"</text>}
}
<li><a @RouterLink("Index","Home")>Home</a></li>
public static class LinkExtensions
{
public static IHtmlContent ActiveActionLink(this IHtmlHelper html, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
{
return ActiveActionLink(html, linkText, actionName, controllerName, new RouteValueDictionary(routeValues), HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static IHtmlContent ActiveActionLink(this IHtmlHelper html, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)
{
var routeData = html.ViewContext.RouteData;
var routeAction = (string)routeData.Values["action"];
var routeController = (string)routeData.Values["controller"];
var active = controllerName.Equals(routeController) && actionName.Equals(routeAction);
using (var writer = new StringWriter())
{
writer.WriteLine($"<li class='nav-item {(active ? "active" : "")}'>");
html.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes).WriteTo(writer, HtmlEncoder.Default);
writer.WriteLine("</li>");
return new HtmlString(writer.ToString());
}
}
}
<nav class="navbar">
<div class="collapse navbar-collapse">
<ul class="navbar-nav">
@Html.ActiveActionLink("Home", "Index", "Home", null, new { @class = "nav-link" })
@Html.ActiveActionLink("About", "About", "Home", null, new { @class = "nav-link" })
@Html.ActiveActionLink("Contact", "Contact", "TimeTracking", null, new { @class = "nav-link" })
</ul>
</div>
</nav>
[HtmlTargetElement("li", Attributes = "active-when")]
public class LiTagHelper : TagHelper
{
public string ActiveWhen { get; set; }
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContextData { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (ActiveWhen == null)
return;
var targetController = ActiveWhen.Split("/")[1];
var targetAction = ActiveWhen.Split("/")[2];
var currentController = ViewContextData.RouteData.Values["controller"].ToString();
var currentAction = ViewContextData.RouteData.Values["action"].ToString();
if (currentController.Equals(targetController) && currentAction.Equals(targetAction))
{
if (output.Attributes.ContainsName("class"))
{
output.Attributes.SetAttribute("class", $"{output.Attributes["class"].Value} active");
}
else
{
output.Attributes.SetAttribute("class", "active");
}
}
}
}
@addTagHelper *, YourAssemblyName
<li active-when="/Home/Index">
[HtmlTargetElement("a", Attributes = "active-then")]
[HtmlTargetElement("a", Attributes = "asp-action")]
[HtmlTargetElement("a", Attributes = "asp-controller")]
public class AnchorActiveTagHelper : AnchorTagHelper
{
public AnchorActiveTagHelper(IHtmlGenerator generator) : base(generator)
{
}
[HtmlAttributeName("active-then")]
public string ActiveWhen { get; set; }
[ViewContext] [HtmlAttributeNotBound] public ViewContext ViewContextData { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
if (ActiveWhen == null)
return;
var currentController = ViewContextData.RouteData.Values["controller"].ToString();
var currentAction = ViewContextData.RouteData.Values["action"].ToString();
if (currentController.Equals(Controller) && currentAction.Equals(Action))
{
if (output.Attributes.ContainsName("class"))
{
output.Attributes.SetAttribute("class", $"{output.Attributes["class"].Value} active");
}
else
{
output.Attributes.SetAttribute("class", "active");
}
}
}
}
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, YourProject.PlatformExtensions
<li class="nav-item">
<a asp-controller="Home" asp-action="Index" class="nav-link" active-then="active">
<i class="nav-icon fas fa-home"></i>
<p>Home</p>
</a>
</li>