如何在ASP.NET Core中创建MVC5 MvcHtmlString
我想知道是否有人可以帮助演示如何在ASP.NET Core中创建IHtmlContent或HtmlString,这与我以前在MVC5中完成的操作类似。我通常一个助手类中声明一个新的MvcHtmlString方法,像这样:如何在ASP.NET Core中创建MVC5 MvcHtmlString
HtmlExtender.cs
要在视图中使用这个@Html.MenuLink("Home", "Home", "Index", "", "Home")
也@using WebApplication1.Helpers
在视图顶部列入。
我不确定使用HtmlString或IHtmlContent来实现我所需要的,但是我的方法需要访问HttpContextAccessor,但我有点不确定如何执行此操作。
我已经在Startup.cs中声明了HttpContextAccessor,因为我相信ASP.NET Core 2.0中它没有默认声明,如下所示,但需要帮助以了解如何在辅助方法中使用。
Startup.cs
public void ConfigureServices(IServiceCollection serviceCollection)
{
serviceCollection.AddMvc();
serviceCollection.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
任何帮助,将不胜感激:-)
在MVC核心的新的原语是好的,易于使用。 TagBuilder实现了IHtmlContent,它可以并且应该在当前使用MvcHtmlString的任何地方使用。对于上述示例,只需删除MvcHtmlString.Create并直接返回TagBuilder(调整为返回IHtmlContent)。
其他有用的类是HtmlContentBuilder,另一种类型返回IHtmlContent,它可以AppendHtml,类似于StringBuilder,但是专门用于HTML内容。你可以添加很多标签构建器,这非常方便。
这是理论上你以后(我发现这个GetUrlHelper扩展在其他地方,我忘记了在哪里)。
public static IUrlHelper GetUrlHelper(this IHtmlHelper html)
{
var urlFactory = html.ViewContext.HttpContext.RequestServices.GetRequiredService<IUrlHelperFactory>();
var actionAccessor = html.ViewContext.HttpContext.RequestServices.GetRequiredService<IActionContextAccessor>();
return urlFactory.GetUrlHelper(actionAccessor.ActionContext);
}
public static IHtmlContent MenuLink(this IHtmlHelper htmlHelper, string linkText, string controller, string action, string area, string anchorTitle)
{
var urlHelper = htmlHelper.GetUrlHelper();
var url = urlHelper.Action(action, controller, new { area });
var anchor = new TagBuilder("a");
anchor.InnerHtml.Append(linkText);
anchor.MergeAttribute("href", url);
anchor.Attributes.Add("title", anchorTitle);
var listItem = new TagBuilder("li");
listItem.InnerHtml.AppendHtml(anchor);
if (CheckForActiveItem(htmlHelper, controller, action, area))
{
listItem.GenerateId("menu_active", "_");
}
return listItem;
}