Javascript 在mvc运行时将css类应用于菜单项
我正在开发一个MVC4应用程序 我有以下菜单项Javascript 在mvc运行时将css类应用于菜单项,javascript,jquery,asp.net-mvc,asp.net-mvc-4,Javascript,Jquery,Asp.net Mvc,Asp.net Mvc 4,我正在开发一个MVC4应用程序 我有以下菜单项 <ul class="menu left"> <li>@Html.ActionLink("Home", "Index", new { Controller = "Home" }, new { @class = "active" })</li> <li>@Html.ActionLink("About Us", "About", new {
<ul class="menu left">
<li>@Html.ActionLink("Home", "Index", new { Controller = "Home" }, new { @class = "active" })</li>
<li>@Html.ActionLink("About Us", "About", new { Controller = "Home" })</li>
<li>@Html.ActionLink("Services", "Services", new { Controller = "Home" })</li>
<li>@Html.ActionLink("Post Job", "Create", new { Controller = "JobPosting" })</li>
<li>@Html.ActionLink("Job Search", "Index", new { Controller = "JobPosting" })</li>
<li>@Html.ActionLink("Contact Us", "Contact", new { Controller = "Home" })</li>
</ul>
- @ActionLink(“Home”,“Index”,new{Controller=“Home”},new{@class=“active”})
- @ActionLink(“关于我们”,“关于”,新的{Controller=“Home”})
- @ActionLink(“服务”,“服务”,新{Controller=“Home”})
- @ActionLink(“发布作业”,“创建”,新建{Controller=“jobsposting”})
- @ActionLink(“工作搜索”,“索引”,new{Controller=“jobsposting”})
- @ActionLink(“联系我们”,“联系”,新建{Controller=“Home”})
现在我想,如果我点击除Home之外的项目,它的css类将变为active。
基本上我只想改变菜单项的颜色
如何动态地进行此操作?如果您想根据您可以使用的操作或控制器更改css
@{
var controller = ViewContext.RouteData.Values["Controller"].ToString();
var action = ViewContext.RouteData.Values["Action"].ToString();
}
<li>
@if (action == "Home") {
@Html.ActionLink("Home", "Index", new { Controller = "Home" },new {@class="active" })
}
else {
@Html.ActionLink("Home", "Index", new { Controller = "Home" })
}
</li>
<li>
@if (action == "About Us") {
@Html.ActionLink("About Us", "About", new { Controller = "Home" },new {@class="active" })
}
else {
@Html.ActionLink("About Us", "About", new { Controller = "Home" })
}
</li>
@{
var controller=ViewContext.RouteData.Values[“controller”].ToString();
var action=ViewContext.RouteData.Values[“action”].ToString();
}
@如果(操作==“主”){
@ActionLink(“Home”,“Index”,new{Controller=“Home”},new{@class=“active”})
}
否则{
@ActionLink(“Home”,“Index”,new{Controller=“Home”})
}
@如果(动作==“关于我们”){
@ActionLink(“关于我们”,“关于”,新的{Controller=“Home”},新的{@class=“active”})
}
否则{
@ActionLink(“关于我们”,“关于”,新的{Controller=“Home”})
}
等等
然后可以在视图中使用此帮助器
@Html.NavActive("Index", "Home")
比如说,
<li>
<a href="~/Home/Index" class="@Html.NavActive("Index", "Home")">
<span>Index</span>
</a>
</li>
这种方法有效,但效果不好。太多的逻辑和代码重复是的,它只是向他展示了如何进行重构Hanks K.A.G,它完成了trikc
<li>
<a href="~/Home/Index" class="@Html.NavActive("Index", "Home")">
<span>Index</span>
</a>
</li>