ASP.NET MVC:突出显示当前链接

时间:2015-02-03 05:48:15

标签: asp.net asp.net-mvc

我需要突出显示菜单中的当前链接,但HTML的结构如下所示:

<li class="active">
    <a href='@Url.Action("MainPage", "Ticket")'>
        <i class="fa  fa-fw fa-home"></i>
        HomePage
    </a>
</li>

我知道有很多不同的解决方案(++):

public static MvcHtmlString MenuLink(
            this HtmlHelper helper,
            string text, string action, string controller)
        {
            var routeData = helper.ViewContext.RouteData.Values;
            var currentController = routeData["controller"];
            var currentAction = routeData["action"];

            if (String.Equals(action, currentAction as string,
                      StringComparison.OrdinalIgnoreCase)
                &&
               String.Equals(controller, currentController as string,
                       StringComparison.OrdinalIgnoreCase))
            {
                return helper.ActionLink(
                    text, action, controller, null,
                    new { @class = "active" }
                    );
            }
            return helper.ActionLink(text, action, controller);
        }

但我的HTML结构有点不同 我怎么能这样做?
有什么想法吗?

1 个答案:

答案 0 :(得分:0)

最后我用这种方式更改了代码并且它有效:(感谢@Stephen Muecke)

public static MvcHtmlString MenuLink(
            this HtmlHelper helper,
            string content, string action, string controller)
        {
            var routeData = helper.ViewContext.RouteData.Values;
            var currentController = routeData["controller"];
            var currentAction = routeData["action"];

            var builder = new TagBuilder("li")
            {
                InnerHtml = content
            };
            if (String.Equals(action, currentAction as string,
                      StringComparison.OrdinalIgnoreCase)
                &&
               String.Equals(controller, currentController as string,
                       StringComparison.OrdinalIgnoreCase))
            {
                builder.AddCssClass("active");
                return MvcHtmlString.Create(builder.ToString());
            }
            return MvcHtmlString.Create(builder.ToString());
        }