Mic*_*ael 65 asp.net-mvc master-pages menu asp.net-mvc-3
我一直在扫描,试图找到一个合适的解决方案,为主页面中的菜单项分配"活动/当前"类.关于是否执行此客户端与服务器端,该线路在中间分开.
说实话,我是JavaScript和MVC的新手,所以我没有意见.我更愿意以"最干净"和最恰当的方式做到这一点.
我有以下jQuery代码将"活动"类分配给<li>项...唯一的问题是"索引"或默认视图菜单项将始终分配活动类,因为URL始终是子字符串其他菜单链接:
(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
}
});
Run Code Online (Sandbox Code Playgroud)
伙计们,有更好的方法吗?有人至少会帮助我获得客户端版本的防弹吗?那么"索引"或默认链接总是"活跃"?有没有办法为索引方法分配假扩展?喜欢而不仅仅是基本URL localhost/home/dashboard,它不会是每个链接的子串?
说实话,我并没有真正遵循做这个服务器端的方法,这就是为什么我试图用jQuery做客户端...任何帮助将不胜感激.
Dar*_*rov 114
自定义HTML帮助程序通常可以正常工作:
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);
}
Run Code Online (Sandbox Code Playgroud)
并在您的母版页中:
<ul>
<li>@Html.MenuLink("Link 1", "link1", "Home")</li>
<li>@Html.MenuLink("Link 2", "link2", "Home")</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
现在剩下的就是定义.current CSS类.
增加了对区域的支持:
public static class MenuExtensions
{
public static MvcHtmlString MenuItem(this HtmlHelper htmlHelper, string text, string action, string controller, string area = null)
{
var li = new TagBuilder("li");
var routeData = htmlHelper.ViewContext.RouteData;
var currentAction = routeData.GetRequiredString("action");
var currentController = routeData.GetRequiredString("controller");
var currentArea = routeData.DataTokens["area"] as string;
if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentArea, area, StringComparison.OrdinalIgnoreCase))
{
li.AddCssClass("active");
}
li.InnerHtml = htmlHelper.ActionLink(text, action, controller, new {area}, null).ToHtmlString();
return MvcHtmlString.Create(li.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24667 次 |
| 最近记录: |