SzymonG27
SzymonG27

Reputation: 26

How to fix a problem with IURLHelper (add singleton on startup.cs doesn't work) ASP.NET Core 2.2

I was trying to create a pagination of my website. I'm learning from book "ASP.NET Core 2" Adam Freeman. These lines:
IUrlHelper urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);
TagBuilder result = new TagBuilder("div");

return null. What is the problem?

This is a asp.net core 2.2 application.

Code that doesn't work:

public override void Process(TagHelperContext context, TagHelperOutput output)
{
     IUrlHelper urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);
     TagBuilder result = new TagBuilder("div");
     for (int i = 1; i <= PageModel.TotalPages; i++)
     {
          TagBuilder tag = new TagBuilder("a");
          tag.Attributes["href"] = urlHelper.Action(PageAction, new { ProductPage = i });
          tag.InnerHtml.AppendHtml(tag);
     }
     output.Content.AppendHtml(result.InnerHtml);
}

I added this to a startup.cs:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(factory =>
{
     var actionContext = factory.GetService<IActionContextAccessor>().ActionContext;
     return new UrlHelper(actionContext);
});

I added a unit tests and It's should return a <a href="test/pageX"></a> for all the pages, but it's return nothing.

Upvotes: 1

Views: 232

Answers (1)

Majid Ali Khan Quaid
Majid Ali Khan Quaid

Reputation: 46

You mistakenly added the anchor to itself, rather trying adding it to the container div

TagBuilder result = new TagBuilder("div");
for (int i = 1; i <= PageModel.TotalPages; i++)
{
     TagBuilder tag = new TagBuilder("a");
     tag.Attributes["href"] = urlHelper.Action(PageAction, new { ProductPage = i });     
     // tag was being added to itself, rather add it the container `div`
     // tag.InnerHtml.AppendHtml(tag);
     result.InnerHtml.AppendHtml(tag);

}

Upvotes: 3

Related Questions