更好的方式来获得MVC 3剃须刀活动页面链接 [英] Better way to get active page link in MVC 3 Razor

查看:107
本文介绍了更好的方式来获得MVC 3剃须刀活动页面链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想要一个特定的菜单链接是活跃在给定的页面,我用这种方法在剃刀:

When I want a specific menu link to be active at a given page, I'm using this approach in Razor:

在总体布局我有这些检查:

On the master layout I have these checks:

var active = ViewBag.Active;
const string ACTIVE_CLASS = "current";

if (active == "home")
{
    ViewBag.ActiveHome = ACTIVE_CLASS;
}
if (active == "products")
{
    ViewBag.ActiveProducts = ACTIVE_CLASS;
}

等。

在主布局HTML菜单:

The html menu on the master layout:

<ul>
<li class="@ViewBag.ActiveHome"><a href="/">Home</a></li>
<li class="@ViewBag.ActiveProducts"><a href="@Url.Action("index", "products")">Products</a></li>
</ul>

当指定在一个不同的看法使用的页面布局:

When specifying which layout page to use on a different view:

@{
    ViewBag.Active = "home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

有没有更好的方法来sepcify活动链接,比我目前使用的人?

Is there a better approach to sepcify active links, than the one I'm currently using?

推荐答案

一个更好的办法是使用HTML帮助:

A better approach is to use a HTML helper:

using System.Web.Mvc; 
using System.Web.Mvc.Html;

public static class MenuExtensions
{
    public static MvcHtmlString MenuItem(
        this HtmlHelper htmlHelper, 
        string text,
        string action, 
        string controller
    )
    {
        var li = new TagBuilder("li");
        var routeData = htmlHelper.ViewContext.RouteData;
        var currentAction = routeData.GetRequiredString("action");
        var currentController = routeData.GetRequiredString("controller");
        if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
            string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
        {
            li.AddCssClass("active");
        }
        li.InnerHtml = htmlHelper.ActionLink(text, action, controller).ToHtmlString();
        return MvcHtmlString.Create(li.ToString());
    }
}

和则:

<ul>
    @Html.MenuItem("Home", "Home", "Home")
    @Html.MenuItem("Products", "Index", "Products")
</ul>

为了让你需要你的意见,认可你的扩展上面的工作:在Web.config文件中的视图文件夹中添加&LT;添加命名空间=yourNamespacehere.Helpers/&GT; 的命名空间标签内。然后建立您的项目,关闭并重新打开要添加这个到视图。

To make the above work you need your views to recognize your extension: In Web.config in the Views folder, add <add namespace="yourNamespacehere.Helpers" /> inside the namespaces tag. Then build your project and close and re-open the view you are adding this to.

然后生成锚时,基于当前操作和控制的助手将添加或不有效类。

then based on the current action and controller the helper will add or not the active class when generating the anchor.

这篇关于更好的方式来获得MVC 3剃须刀活动页面链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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