mvc5 html5,c# - How to create a MVC5 MvcHtmlString in ASP.NET Core - Stack Overflow

I wonder if someone can help with demonstrating how to create a IHtmlContent or HtmlString in ASP.NET Core, similar to what I previously have done in MVC5. I would normally declare a new MvcHtmlString method within a Helper class like so:

HtmlExtender.cs

using System.Text;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

namespace WebApplication1.Helpers

{

public static class HtmlExtender

{

public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, string linkText, string controller, string action, string area, string anchorTitle)

{

var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

var url = urlHelper.Action(action, controller, new { area });

var anchor = new TagBuilder("a") {InnerHtml = HttpUtility.HtmlEncode(linkText)};

anchor.MergeAttribute("href", url);

anchor.Attributes.Add("title", anchorTitle);

var listItem = new TagBuilder("li") {InnerHtml = anchor.ToString(TagRenderMode.Normal)};

if (CheckForActiveItem(htmlHelper, controller, action, area))

{

listItem.GenerateId("menu_active");

}

return MvcHtmlString.Create(listItem.ToString(TagRenderMode.Normal));

}

private static bool CheckForActiveItem(HtmlHelper htmlHelper, string controller, string action, string area)

{

if (!CheckIfTokenMatches(htmlHelper, area, "area"))

return false;

if (!CheckIfValueMatches(htmlHelper, controller, "controller"))

return false;

return CheckIfValueMatches(htmlHelper, action, "action");

}

}

}

To use in a View would be @Html.MenuLink("Home", "Home", "Index", "", "Home") also the inclusion of @using WebApplication1.Helpers at the top of the View.

I'm unsure as to the use of HtmlString or IHtmlContent to achieve what I need, but my method requires access to the HttpContextAccessor, but I am a little unsure how to do this.

I have declared the HttpContextAccessor in the Startup.cs as I believe in ASP.NET Core 2.0 it is not declared by default as shown below but require assistance as how to use within the helper method.

Startup.cs

public void ConfigureServices(IServiceCollection serviceCollection)

{

serviceCollection.AddMvc();

serviceCollection.AddSingleton();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值