自定义ActionLink的帮手知道你在什么页面上 [英] Custom ActionLink helper that knows what page you're on

查看:103
本文介绍了自定义ActionLink的帮手知道你在什么页面上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Html.ActionLink帮手导航栏一小MVC的网站。有一件事我想改变的是,默认的ActionLink会呈现出一个html的网页链接,即使是当前页面。

I have a small MVC site that uses the Html.ActionLink helper for a navbar. One thing I would like to change is that the default ActionLink will render out an html link to a page even if that is the current page.

例如,它会创建这样一个链接:

For example, it creates a link like this:

<a href="/myUrl">Some title...</a>

即使你已经在/ myUrl。这将是很好,如果它会禁用该链接,也许插入一个特殊的CSS类来显示当前访问的页面,如下所示:

even if you're already on /myUrl. It would be nice if it would disable that link and maybe insert a special CSS class to show the currently visited page, like this:

<a href="#" class="currentPageCSS">My Url</a>
<a href="/someOtherUrl">Some Other Url</a>

此问题必须已经遇到过的MVC网站的负载,所以我很好奇,想知道其他人如何解决它。

This problem must have been encountered before on loads of MVC sites, so I'm curious to know how other people have tackled it.

推荐答案

这似乎是一个好方案推出的自定义HTML帮手。因此,让我们滚吧:

This seems like a good scenario to roll a custom HTML helper. So let's roll it:

public static class LinkExtensions
{
    public static MvcHtmlString MyActionLink(
        this HtmlHelper htmlHelper, 
        string linkText, 
        string action, 
        string controller
    )
    {
        var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
        var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
        if (action == currentAction && controller == currentController)
        {
            var anchor = new TagBuilder("a");
            anchor.Attributes["href"] = "#";
            anchor.AddCssClass("currentPageCSS");
            anchor.SetInnerText(linkText);
            return MvcHtmlString.Create(anchor.ToString());
        }
        return htmlHelper.ActionLink(linkText, action, controller);
    }
}

和您的视图中:

<%= Html.MyActionLink("hello foo", "Index", "Home") %>
<%= Html.MyActionLink("hello bar", "About", "Home") %>
...

和根据你所在的助手将生成适当的锚上。

and depending on where you are the helper will generate the proper anchor.

这篇关于自定义ActionLink的帮手知道你在什么页面上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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