在ASP.NET 5 MVC6 RC1中-我有一个ViewComponent,旨在代表我的传统“屏幕左侧”主菜单。
我正在编写我的第一个TagHelper来代表每个菜单项链接。
我被困在试图创建超链接的部分。
我该如何解决 ~/dashboard/summary?
如果我在此页面上显示菜单,则链接显示为/dashboard/~/dashboard/summary
。
@Url.Content("...")
显示@Url.Content("...")
即未作为剃刀处理。标记帮助器输出pure。
理想情况下,我希望该解决方案与.NET Core兼容,因为我最终的目标是.NET Core可部署解决方案。
见下文:
namespace Website { ////// [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"); } ////// /// to render /// /// /// Change my password
/// /// /// ///} }
谢谢!担。
默认情况下,ASP Core 2.0似乎未包含IActionContextAccessor
在中IServiceCollection
,因此您需要在启动时进行注册才能使接受的解决方案起作用:
services.AddSingleton();
否则,提供的属性可以将的属性设置TagHelper
为,ViewContext
从而扩展了ActionContext
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
属性必须具有公共设置方法