了解用户在 .NET Core 中的 TagHelper 中的路由 [英] Knowing what route the user is on inside TagHelper in .NET Core

查看:26
本文介绍了了解用户在 .NET Core 中的 TagHelper 中的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 .NET Core 应用程序.我有一个带有一些链接的侧边栏.当我单击特定链接时,我想将 active CSS 类应用于其列表项.

I am working on a .NET Core application. I have a sidebar with some links. When I click on a particular link, I want to apply the active CSS class to its list item.

<li class="active ">
  <a href="home/index">
    <i class="material-icons">home</i>
    <span class="title">Home</span>
  </a>
</li>

我过去可以使用 .NET Framework 4.6 中的 Html Helpers 执行此操作,但我不知道如何在 .NET Core 中执行此操作.我希望标签助手的最终结果如下所示:

I use to be able to do this with Html Helpers in .NET Framework 4.6 but I do not know how to do it in .NET Core. I want the end result of the tag helper to look like this:

<sidebarlink controller="home" action="index" icon="home"></sidebarlink>

根据我在 .NET Framework 4.6 中所做的工作,我进行了尝试,但无法使其适用于新的标签助手.

Based on what I did in .NET Framework 4.6, I have made an attempt but I cannot get it to work for the new Tag Helpers.

public class SidebarLink : TagHelper
{
  private const string ActiveClass = "active";

  public string Controller { get; set; }

  public string Action { get; set; }

  public string Icon { get; set; }

  public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
  {
    output.TagName = "li";
    var content = await output.GetChildContentAsync();
    content.SetHtmlContent($@"<a href=\"/Controller/Action\"><i class=\"material-icons\">Icon</i><span class=\"title\">Suppliers</span></a>"); // this doesn't work, something is up with the syntax
    // only if I am on the route for the passed controller and action
    // not sure how to check
    output.Attributes.SetAttribute("class", ActiveClass);
  }
}

我不知道如何检查我是否在与传递的控制器和操作匹配的路由上,以便我可以应用 active 类.

I do not know how I can check and see if I am on the route matching the passed Controller and Action so that I may apply the active class.

推荐答案

将以下属性添加到您的标签助手:

Add the following property to your tag helper:

[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }

然后,您可以通过以下方式获取当前控制器/动作:

Then, you can get the current controller/action via:

var controller = ViewContext.RouteData.Values["controller"]
var action = ViewContext.RouteData.Values["action"]

这篇关于了解用户在 .NET Core 中的 TagHelper 中的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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