gpt4 book ai didi

c# - 如何解析来自 TagHelper 的 ~ 根链接

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:34 24 4
gpt4 key购买 nike

在 ASP.NET 5 MVC6 RC1 中——我有一个 ViewComponent,它旨在代表我传统的“屏幕左侧”主菜单。

我正在编写我的第一个 TagHelper 来表示每个菜单项链接。

我卡在了尝试创建超链接的部分。

如何解决 ~/dashboard/summary?

如果我在此页面上显示菜单,链接显示为 /dashboard/~/dashboard/summary

@Url.Content("...") 显示 @Url.Content("...") 即不作为 Razor 处理。标签助手输出纯。

理想情况下,我希望解决方案与 .NET Core 兼容,因为我最终的目标是 .NET Core 可部署解决方案。

见下文:

namespace Website
{

/// <summary>
/// <MainMenuLink area="" controller="" action=""></MainMenuLink>
///
/// to render
///
/// <a href="~/account/manage/ChangePassword" class="list-group-item @GetClassName("manage", "changepassword")">
/// <p class="list-group-item-text"><i class="fa fa-terminal"></i>&nbsp;&nbsp;Change my password</p>
/// </a>
///
///
/// </summary>
[HtmlTargetElement(Attributes = "area, controller, action")]
public class MainMenuLinkTagHelper : TagHelper
{
[HtmlAttributeName("area")]
public string Area { get; set; }

[HtmlAttributeName("controller")]
public string Controller { get; set; }

[HtmlAttributeName("action")]
public string Action { get; set; }

public UrlHelper urlHelper { get; set; }

public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "a"; // Works
// Stuck here - I want ~/ to resolve to the base root.
// At the moment the address is here is localhost:XXXXX/dashboard/~/dashboard/summary

// Would prefer to use a method which can be used with .net core and not System.Web

output.Attributes.Add("href", "~/dashboard/summary");
output.Content.SetHtmlContent("Click me");

}
/// <summary>
}
}

谢谢!丹.

最佳答案

ASP Core 2.0 默认情况下似乎没有在 IServiceCollection 中包含 IActionContextAccessor,因此您需要在启动时注册它以接受工作解决方案:

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

否则,提供的属性可以将 TagHelper 的属性设置为扩展 ActionContextViewContext

using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

[HtmlTargetElement("my-tag")]
public class MyTagHelper : TagHelper {

private readonly IUrlHelperFactory urlHelperFactory;

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

public MyTagHelper (IUrlHelperFactory urlHelperFactory) {
this.urlHelperFactory = urlHelperFactory;
}

public override void Process(TagHelperContext context, TagHelperOutput output) {
var urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);
}
}

注意:ViewContext 属性必须有一个公共(public)设置方法

关于c# - 如何解析来自 TagHelper 的 ~ 根链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34385547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com