Migrating TagBuilder core methods from ASP.NET MVC 5 to ASP.NET Core (.NET 5)

1.5k views Asked by At

I have a web app developed with ASP.NET MVC 5 and I have to migrate it to ASP.NET Core (.NET 5). I had some extesion methods for HtmlHelper to get glyph icon with a link:

public static MvcHtmlString GlyphiconActionLink(this HtmlHelper helper, string action, string controller, object parameters, string glyphiconTag, string title)
{
    TagBuilder span = new TagBuilder("span");
    span.MergeAttribute("class", $"glyphicon {glyphiconTag}");
    span.MergeAttribute("title", title);

    string url = UrlHelper.GenerateUrl(
        null, action, controller, new RouteValueDictionary(parameters),
        helper.RouteCollection, helper.ViewContext.RequestContext, true);

    TagBuilder link = new TagBuilder("a");
    link.MergeAttribute("href", url);
    link.InnerHtml = span.ToString(TagRenderMode.SelfClosing);

    return MvcHtmlString.Create(link.ToString());
}

In Razor pages I could write this

@Html.GlyphiconActionLink("Details", "MyController", new { id = model.Id }, "glyphicon-pencil", "Show to details")

To get this HTML:

<a href="/mycontroller/details/1"><span class="glyphicon glyphicon-pencil" title="Details" /></a>

Now, in .NET Core, this code doesn't work, it have many errors.

Changes I did:

  • Return value from System.Web.Mvc.MvcHtmlString to Microsoft.AspNetCore.Html.HtmlString, returning return new HtmlString(link.ToString());.
  • From link.InnerHtml = span.ToString(TagRenderMode.SelfClosing) to link.InnerHtml.Append(span.ToString(TagRenderMode.SelfClosing)).

The errors I have are:

  • UrlHelper.GenerateUrl: 'GenerateUrl' is inaccessible due to its protection level.
  • helper.RouteCollection: 'HtmlHelper' does not contain a definition for 'RouteCollection'.
  • helper.ViewContext.RequestContext: 'ViewContext' does not contain a definition for 'RequestContext'.
  • span.ToString(TagRenderMode.SelfClosing): No overload for method 'ToString' takes 1 arguments.

Do you know how to migrate it?

0

There are 0 answers