我的母版页中有以下菜单:
<ul id="menu" class="lavaLampBottomStyle">
<li>
<%= Html.ActionLink("Employees", "Index", "Employees")%></li>
<li>
<%= Html.ActionLink("Customer", "Details", "Account")%></li>
</ul>
我需要一种方法来将当前事件的 li 的 css 类设置为“当前”。
我的第一个猜测是借助 javascript 来完成此操作。
我会在母版页中包含这样的内容:
$("#menu li a").each(){
if($(this).attr("href") == '<%= *GET CURRENT PAGE* %>'){
$(this).parent("li").addClass("current");
}
}
这是一个好方法吗?
如果是,我怎样才能像 href 中那样获取当前 URL 部分?
如果不是,您有什么建议? :-)
仅供引用,我要生成的 html:
<ul id="menu" class="lavaLampBottomStyle">
<li>
<a href="/KszEmployees/Index">Employees</a></li>
<li>
<a class="current" href="/">Customer</a></li>
</ul>
最佳答案
如果你想全部在服务器端完成,我以前做过。创建 Action 过滤器属性:
public class PageOptionsAttribute : ActionFilterAttribute
{
public string Title { get; set; }
public string Section { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = filterContext.Controller as ControllerBase;
if (controller != null)
{
controller.SetPageSection(this.Section);
controller.SetPageTitle(this.Title);
}
base.OnActionExecuting(filterContext);
}
}
这会调用我所有 Controller 继承自的 ControllerBase 类中的两个方法:
public class ControllerBase : Controller
{
public void SetPageSection(string section)
{
// use the section defined or the controller name if none
ViewData["PageSection"] = section != null ?
section : this.RouteData.Values["controller"].ToString();
}
public void SetPageTitle(string title)
{
ViewData["PageTitle"] = title;
}
}
在 Controller 方法上设置标题和页面部分:
public class HomeController : ControllerBase
{
[PageOptions(Title="Home Page", Section="Home")]
public ActionResult Index()
{ }
}
然后我从母版页调用 ViewData 值(这不会干扰 ViewData.Model):
<body class="<%=ViewData["PageSection"] %>">
然后通过 CSS 引用,而不是调用 .current,给每个导航项一个 ID,然后结合使用 body 类和该 ID 来确定当前页面。
body.home #HomeNav { /* selected */ }
body.about #AboutNav { /* selected */ }
关于javascript - ASP.NET MVC : Masterpage: How to set css class on active menu item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/945177/