活动菜单项 - asp.net MVC3母版页 [英] active menu item - asp.net mvc3 master page
问题描述
我一直在四处扫描试图找到从母版页分配主动/当前类的菜单项相应的解决方案。该生产线是中间拆了下来与是否做这个客户端VS服务器端的问候。
I've been scanning around trying to find an appropriate solution for assigning "active/current" class to menu items from the master page. The line is split down the middle with regards of whether to do this client vs server side.
说实话我是新来的JavaScript和MVC所以我没有意见。我想preFER要做到这一点,在干净,最恰当的方式。
Truthfully I'm new to both JavaScript and MVC so i don't have an opinion. I would prefer to do this in the "cleanest" and most appropriate way.
我有以下的jQuery code分配活动类的<立GT;项目......唯一的问题是指数或默认视图菜单项将始终分配活动类,因为URL始终是其它菜单链接的子串:
I have the following jQuery code to assign the "active" class to the <li> item...the only problem is the "index" or default view menu item will always be assigned the active class, because the URL is always a substring of the other menu links:
(default) index = localhost/
link 1 = localhost/home/link1
link 2 = localhost/home/link1
$(function () {
var str = location.href.toLowerCase();
$('#nav ul li a').each(function() {
if (str.indexOf(this.href.toLowerCase()) > -1) {
$(this).parent().attr("class","active"); //hightlight parent tab
}
});
是否有这样做,伙计们一个更好的办法?有人会至少帮我把客户端版本防弹?使指数或默认链接始终是激活?是否有分配一个假扩展到索引方法的一种方式?像而不只是基本URL这将是本地主机的/ home /仪表板
,这样它不会是每个环节的一个子?
Is there a better way of doing this, guys? Would someone at least help me get the client-side version bulletproof? So that the "index" or default link is always "active"? Is there a way of assigning a fake extension to the index method? like instead of just the base URL it would be localhost/home/dashboard
so that it wouldn't be a substring of every link?
说实话,我真的不遵循这样的服务器端,这就是为什么我试图用jQuery做客户端的方法...任何帮助,将AP preciated。
Truthfully, i don't really follow the methods of doing this server-side, which is why I'm trying to do it client side with jQuery...any help would be appreciated.
推荐答案
自定义HTML帮助通常做工作罚款:
A custom HTML helper usually does the job fine:
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 = "current"
});
}
return htmlHelper.ActionLink(linkText, actionName, controllerName);
}
和在你的母版页:
<ul>
<li>@Html.MenuLink("Link 1", "link1", "Home")</li>
<li>@Html.MenuLink("Link 2", "link2", "Home")</li>
</ul>
现在所有剩下的就是定义.current CSS类。
Now all that's left is define the .current CSS class.
这篇关于活动菜单项 - asp.net MVC3母版页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!