在 MVC 3 Razor 中获取活动页面链接的更好方法 [英] Better way to get active page link in MVC 3 Razor

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

问题描述

当我希望在给定页面上激活特定菜单链接时,我在 Razor 中使用这种方法:

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";
}

是否有比我目前使用的更好的方法来分离活动链接?

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>

要完成上述工作,您需要您的视图来识别您的扩展:在 Views 文件夹中的 Web.config 中,在名称空间内添加 <add namespace="yourNamespacehere.Helpers"/>标签.然后构建您的项目并关闭并重新打开要添加到的视图.

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.

然后根据当前的动作和控制器,助手将在生成锚点时添加或不添加 active 类.

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

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

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