ASP.net MVC - 导航并突出显示“当前”内容关联

发布于 2024-09-30 15:33:06 字数 691 浏览 0 评论 0 原文

当您创建一个新的 MVC 项目时,它会创建一个具有以下标记的 Site.master:

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

我想在此处放置代码,如果我在该页面上,它将突出显示当前链接。

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

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

如果我在产品控制器中进行任何操作,我希望产品链接处于活动状态(使用 .active 之类的 css 类)。

如果我处于 HomeController 关于操作,则“关于”链接应该处于活动状态。如果我正在执行 HomeController 的 Index 操作,则 Home 链接应该处于活动状态。

在 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>

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>

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.

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.

What is the best way to do this in MVC?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

贵在坚持 2024-10-07 15:33:06

查看 这篇博文

它展示了如何创建一个您调用的 HTML 扩展,而不是通常的 Html.ActionLink 该扩展然后附加 class="selected"< /code> 到当前活动的列表项。

然后,您可以在 CSS 中添加任何您想要的格式/突出显示

编辑

只需添加一些代码而不仅仅是链接。

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 中定义 selected 类,然后在视图中在顶部添加 using 语句。

@using ProjectNamespace.HtmlHelpers

并使用 MenuLink 而不是 ActionLink

@Html.MenuLink("Your Menu Item", "Action" ,“控制器”)

Check out this blog post

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.

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

EDIT

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);


    }
} 

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

And use the MenuLink instead of ActionLink

@Html.MenuLink("Your Menu Item", "Action", "Controller")

国际总奸 2024-10-07 15:33:06

您可以通过使用“data-”属性来标识容器,然后使用 jQuery 更改链接的 CSS 类来完成此操作,如下所示:

<div class="..." data-navigation="true">
                    <ul class="...">
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
</div>

<script>
    $(function () {
        $("div[data-navigation='true']").find("li").children("a").each(function () {
            if ($(this).attr("href") === window.location.pathname) {
                $(this).parent().addClass("active");
            }
        });
    });
</script>

You could do this by using "data-" attributes to identify the container(s) then using jQuery change CSS class of the link, like the following:

<div class="..." data-navigation="true">
                    <ul class="...">
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
</div>

<script>
    $(function () {
        $("div[data-navigation='true']").find("li").children("a").each(function () {
            if ($(this).attr("href") === window.location.pathname) {
                $(this).parent().addClass("active");
            }
        });
    });
</script>
離殇 2024-10-07 15:33:06

下面是一种将其实现为 MVC 帮助程序的方法:

@helper NavigationLink(string linkText, string actionName, string controllerName)
{
    if(ViewContext.RouteData.GetRequiredString("action").Equals(actionName, StringComparison.OrdinalIgnoreCase) &&
       ViewContext.RouteData.GetRequiredString("controller").Equals(controllerName, StringComparison.OrdinalIgnoreCase))
    {
        <span>@linkText</span>
    }
    else
    {
        @Html.ActionLink(linkText, actionName, controllerName);
    }
}

然后可以类似于以下方式使用它:

@NavigationLink("Home", "index", "home")
@NavigationLink("About Us", "about", "home")

可以在此处找到有关 MVC 帮助程序的好文章: http://weblogs.asp.net/scottgu/archive/ 2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

Here is a way to implement this as an MVC helper:

@helper NavigationLink(string linkText, string actionName, string controllerName)
{
    if(ViewContext.RouteData.GetRequiredString("action").Equals(actionName, StringComparison.OrdinalIgnoreCase) &&
       ViewContext.RouteData.GetRequiredString("controller").Equals(controllerName, StringComparison.OrdinalIgnoreCase))
    {
        <span>@linkText</span>
    }
    else
    {
        @Html.ActionLink(linkText, actionName, controllerName);
    }
}

It can then be used similar to the following:

@NavigationLink("Home", "index", "home")
@NavigationLink("About Us", "about", "home")

A good article on MVC helpers can be found here: http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

请叫√我孤独 2024-10-07 15:33:06

我将这种方法与 htmlhelper 一起使用来解决问题:

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.Equals(currentAction, StringComparison.InvariantCultureIgnoreCase) && controllerName.Equals(currentController, StringComparison.InvariantCultureIgnoreCase))
        {
            return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = "active" });
        }

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

    }
}

以及视图

@Html.MenuLink"Linktext", "action", "controller")

I Used this approach with a htmlhelper for the problem:

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.Equals(currentAction, StringComparison.InvariantCultureIgnoreCase) && controllerName.Equals(currentController, StringComparison.InvariantCultureIgnoreCase))
        {
            return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = "active" });
        }

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

    }
}

and for the view

@Html.MenuLink"Linktext", "action", "controller")
黑凤梨 2024-10-07 15:33:06

您可能想查看我的 MVC 导航控件系列,其中包括自动突出显示当前链接的功能:

http:// mvcquicknav.apphb.com/

You might like to check out my series of MVC navigation controls, which includes the ability to automatically highlight the current link:

http://mvcquicknav.apphb.com/

梦巷 2024-10-07 15:33:06

感谢@codingbadger 提供的解决方案。

我必须在多个操作上突出显示我的导航链接,因此我决定添加更多包含控制器操作对的参数,如果也访问了这些组合中的任何一个,它将突出显示链接。而且,就我而言,突出显示类将应用于

  • 元素。
  • 我将代码放在这里希望它能帮助将来的人:

    • 这是辅助方法:

      /// <摘要>
      /// 该链接在用于重定向时将突出显示,并且在使用 otherActions 参数中指定的任何操作控制器对时也会突出显示。
      /// 
      /// 将应用于所选链接的 CSS 类
      /// 分别包含动作名称和控制器名称对的元组列表
      公共静态MvcHtmlString NavLink(此HtmlHelper htmlHelper,字符串linkText,字符串actionName,字符串controllerName,字符串parentElement,字符串selectedClass,IEnumerable > otherActions)
      {
          字符串 currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
          字符串 currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("控制器");
      
          if ((actionName == currentAction &&controllerName == currentController) || 
              (otherActions != null && otherActions.Any(pair =>pair.Item1 == currentAction &&pair.Item2 == currentController)))
          {
              return new MvcHtmlString($"<{parentElement} class=\"{selectedClass}\">{htmlHelper.ActionLink(linkText, actionName, controllerName)}");
          }
      
          返回新的MvcHtmlString($"<{parentElement}>{htmlHelper.ActionLink(linkText,actionName,controllerName)}");
      }
      
    • 这里是如何使用它的示例:

    <ul>
      @Html.NavLink("Check your eligibility", "CheckEligibility", "Eligibility", "li", "current-page", new Tuple<string, string>[]
       {
           new Tuple<string, string>("Index", "Eligibility"),
           new Tuple<string, string>("RecheckEligibility", "Eligibility")
       })
       @Html.NavLink("Apply for my loan", "Apply", "Loan", "li", "current-page")
    </ul>

    Thanks to @codingbadger for the solution.

    I had to get my nav-links highlighted on multiple actions so I decided to add a few more parameters that contain the controller-action pairs and it'll highlight the link if either of those combinations is accessed too. And, in my case, the highlighting class was to be applied to a <li> element.

    I'm putting my code here hoping it will help someone in the future:

    • Here's the helper method:

      /// <summary>
      /// The link will be highlighted when it is used to redirect and also be highlighted when any action-controller pair is used specified in the otherActions parameter.
      /// </summary>
      /// <param name="selectedClass">The CSS class that will be applied to the selected link</param>
      /// <param name="otherActions">A list of tuples containing pairs of Action Name and Controller Name respectively</param>
      public static MvcHtmlString NavLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string parentElement, string selectedClass, IEnumerable<Tuple<string, string>> otherActions)
      {
          string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
          string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
      
          if ((actionName == currentAction && controllerName == currentController) || 
              (otherActions != null && otherActions.Any(pair => pair.Item1 == currentAction && pair.Item2 == currentController)))
          {
              return new MvcHtmlString($"<{parentElement} class=\"{selectedClass}\">{htmlHelper.ActionLink(linkText, actionName, controllerName)}</{parentElement}>");
          }
      
          return new MvcHtmlString($"<{parentElement}>{htmlHelper.ActionLink(linkText, actionName, controllerName)}</{parentElement}>");
      }
      
    • And, here's an example of how to use it:

    <ul>
      @Html.NavLink("Check your eligibility", "CheckEligibility", "Eligibility", "li", "current-page", new Tuple<string, string>[]
       {
           new Tuple<string, string>("Index", "Eligibility"),
           new Tuple<string, string>("RecheckEligibility", "Eligibility")
       })
       @Html.NavLink("Apply for my loan", "Apply", "Loan", "li", "current-page")
    </ul>

    苍暮颜 2024-10-07 15:33:06

    首先创建一个帮助程序类和 HTML 帮助程序方法

     public static string IsActive(this HtmlHelper html,string control,string action)
        {
            var routeData = html.ViewContext.RouteData;
    
            var routeAction = (string)routeData.Values["action"];
            var routeControl = (string)routeData.Values["controller"];
    
            // both must match
            var returnActive = control == routeControl &&
                               action == routeAction;
    
            return returnActive ? "active" : "";
        }
    

    ,然后在视图或布局部分中只需使用适当的控制器和操作调用帮助程序方法。

      @using YourNamespace.HtmlHelpermethodName
    
     <a class="nav-link @Html.IsActive("Dashboard","Index")" href="@Url.Action("Index","Dashboard")">
    

    这将在类属性中添加“active”字符串,它将显示为

     <a class="nav-link active" href="@Url.Action("Index","Dashboard")">
    

    First Make a Helper Class and HTML Helper method

     public static string IsActive(this HtmlHelper html,string control,string action)
        {
            var routeData = html.ViewContext.RouteData;
    
            var routeAction = (string)routeData.Values["action"];
            var routeControl = (string)routeData.Values["controller"];
    
            // both must match
            var returnActive = control == routeControl &&
                               action == routeAction;
    
            return returnActive ? "active" : "";
        }
    

    And in View or Layour Section Just Call the Helper Method with appropriate Conntroller and Action.

      @using YourNamespace.HtmlHelpermethodName
    
     <a class="nav-link @Html.IsActive("Dashboard","Index")" href="@Url.Action("Index","Dashboard")">
    

    this will add "active" string in class attribute and it will show like

     <a class="nav-link active" href="@Url.Action("Index","Dashboard")">
    
    星軌x 2024-10-07 15:33:06
    public ActionResult SignIn(User user)
    {
        User u = db.Users.Where(p=>p.Email == user.Email & p.Password == user.Password).FirstOrDefault();
        if (u == null)
        {
           return View();
        }
        var id = u.Id;
        Session["id_user"] = id;
    
        return RedirectToAction("Index", "Home");
    }
    
    public ActionResult SignIn(User user)
    {
        User u = db.Users.Where(p=>p.Email == user.Email & p.Password == user.Password).FirstOrDefault();
        if (u == null)
        {
           return View();
        }
        var id = u.Id;
        Session["id_user"] = id;
    
        return RedirectToAction("Index", "Home");
    }
    
    傾旎 2024-10-07 15:33:06
    <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    <li>@Html.ActionLink("Products", "Index", "Products")</li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Archivo<b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <li>@Html.ActionLink("Document Type", "Index", "DocumentTypes")</li>
                            <li>@Html.ActionLink("Employee", "Index", "Employees")</li>
                            <li>@Html.ActionLink("Suppliers", "Index", "Suppliers")</li>
                        </ul>
                    </li>    
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
    
    <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    <li>@Html.ActionLink("Products", "Index", "Products")</li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Archivo<b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <li>@Html.ActionLink("Document Type", "Index", "DocumentTypes")</li>
                            <li>@Html.ActionLink("Employee", "Index", "Employees")</li>
                            <li>@Html.ActionLink("Suppliers", "Index", "Suppliers")</li>
                        </ul>
                    </li>    
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
    
    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文