ASP.net MVC - 导航和突出"本期"链接 [英] ASP.net MVC - Navigation and highlighting the "current" link

查看:105
本文介绍了ASP.net MVC - 导航和突出"本期"链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建它创建了一个Site.master母与下面的标记一个新的MVC项目:

When you create a new MVC project it creates a Site.master with the following markup:

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

我想提出code在这里将突出当前的链接,如果我在该网页。

I would like to put code in here that will highlight the current link if I am on that page.

如果我添加一个链接,如:

If I add another link such as:

<li><%: Html.ActionLink("Products", "Index", "Products")%></li>

我想要的产品链接被激活(使用CSS类一样。主动),如果我在products控制器的任何行动。

I would want the Products link to be active (using a css class like .active) if I'm on any action in the Products controller.

如果我在HomeController中关于采取行动的关于链接应该是积极的。如果我在HomeController中的Index操作的首页链接应该是有效的。

The About link should be active if I'm on the HomeController About action. The Home link should be active if I'm on the Index action of the HomeController.

什么是MVC做到这一点的最好方法是什么?

What is the best way to do this in MVC?

推荐答案

查看<一个href=\"http://geekswithblogs.net/bdiaz/archive/2010/04/09/handy-asp.net-mvc-2-extension-methods-ndash-where-am-i.aspx\">this博客文章

它显示了如何创建你打电话,而不是一个HTML扩展通常的 Html.ActionLink 扩展然后追加类=选择来当前活动的列表项。

It shows how to create an HTML Extension that you call instead of the usual Html.ActionLink The extension then appends class="selected" to the list item that is currently active.

然后,您可以把任何格式/凸显你在CSS希望

You can then put whatever formatting/highlighting you want in your CSS

修改

只是增加了一些code到,而不仅仅是一个链接。

Just adding some code to rather than just a link.

public static class HtmlHelpers
{

    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 = "selected" });
        }

        return htmlHelper.ActionLink(linkText, actionName, controllerName);


    }
} 

现在,你需要在你的CSS来定义你的类,然后在视图中添加在使用语句顶部。

Now you need to define your selected class in your CSS and then in your views add a using statement at the top.

@using ProjectNamespace.HtmlHelpers

和使用 MenuLink 而不是 ActionLink的

@ Html.MenuLink(您的菜单项,行动,控制器)

这篇关于ASP.net MVC - 导航和突出&QUOT;本期&QUOT;链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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