添加和QUOT;积极"标签导航列表中的一个asp.net mvc的母版页 [英] Adding "active" tag to navigation list in an asp.net mvc master page

查看:97
本文介绍了添加和QUOT;积极"标签导航列表中的一个asp.net mvc的母版页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在默认的asp.net mvc的项目,在文件的Site.Master,有一个菜单导航列表:

In the default asp.net mvc project, in the Site.Master file, there is a menu navigation list:

<div id="menucontainer">
    <ul id="menu">              
        <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
        <li><%= Html.ActionLink("About Us", "About", "Home")%></li>
    </ul>
</div>

这使得在浏览器中:

<div id="menucontainer"> 
    <ul id="menu">              
        <li><a href="/">Home</a></li> 
        <li><a href="/Home/About">About Us</a></li> 
    </ul> 
</div>

我希望能够动态地设置活动列表项的基础上,正在被调用的图。也就是说,当用户在看的主页,我就希望创建以下HTML:

I want to be able to dynamically set the active list item, based on the view that is being called. That is, when the user is looking at the home page, I would want the following HTML to be created:

<div id="menucontainer"> 
    <ul id="menu">              
        <li class="active"><a href="/">Home</a></li> 
        <li><a href="/Home/About">About Us</a></li> 
    </ul> 
</div>

我希望,要做到这一点的方法是这样的:

I would expect that the way to do this would be something like:

<div id="menucontainer">
    <ul id="menu">              
        <li <% if(actionName == "Index"){%> class="active"<%}%>><%= Html.ActionLink("Home", "Index", "Home")%></li>
        <li <% if(actionName == "About"){%> class="active"<%}%>><%= Html.ActionLink("About Us", "About", "Home")%></li>
    </ul>
</div>

这里的关键位是&LT;%,如果(actionName ==指数){%GT;类=主动&LT;%}%GT; 行。我不知道如何确定当前actionName是什么。

The key bit here is the <% if(actionName == "Index"){%> class="active"<%}%> line. I do not know how to determine what the current actionName is.

这是如何做到这一点有什么建议?或者,如果我在完全错误的轨道,有没有更好的方式来做到这一点?

Any suggestions on how to do this? Or, if I'm on completely the wrong track, is there a better way to do this?

推荐答案

我自己做了一个辅助的方法来处理这​​种类型的东西。在我的母版页后面的code(可能被推迟到扩展方法...可能是一个更好的方法),我把下面的code。

I made myself a helper method to handle this type of thing. In the code behind of my master page (could be pushed of to an extension method ... probably a better approach), I put the following code.

protected string ActiveActionLinkHelper(string linkText, string actionName, string controlName, string activeClassName)
{
    if (ViewContext.RouteData.Values["action"].ToString() == actionName && 
            ViewContext.RouteData.Values["controller"].ToString() == controlName)
        return Html.ActionLink(linkText, actionName, controlName, new { Class = activeClassName });

    return Html.ActionLink(linkText, actionName, controlName);
}

然后,我只是把它在我的网页像这样:

Then, I just call it in my page like so:

<%= ActiveActionLinkHelper("Home", "Index", "Home", "selected")%>

这篇关于添加和QUOT;积极&QUOT;标签导航列表中的一个asp.net mvc的母版页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆