了解用户在 .NET Core 中的 TagHelper 中的路由

编程入门 行业动态 更新时间:2024-10-27 22:31:28
本文介绍了了解用户在 .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 中的路由

本文发布于:2023-11-15 07:56:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1592581.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   用户   Core   NET   TagHelper

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!