How to pass value to ASP.NET Core custom tag helper?

866 views Asked by At

I'm completely new with custom tag helper. After lots of searching all examples build and pass values but never get values from tag helper.

My Idea is to build a custom pager. So I need to know the number of pages nop. I don't know if I should add dataset attribute to pass the value of nop or there is another way.

I don't know really how the scenario should be. However, I'll try to explain my code here.

First

[HtmlTargetElement(Attributes = "pagination")]
public class Pagerpagination : TagHelper
{
    public int nop { get; set; } // I should get number of pages
    public string BootstraPagination;
    public string pagination { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        BootstraPagination = "<nav><ul class='pagination'>";

        for (int i = 0; i < nop; i++)
        {
            BootstraPagination += $"<li class='page-item'><a class='page-link' href='{i}'>{i + 1}</a></li>";
        }

        BootstraPagination += "</ul></nav>";
        output.Content.SetHtmlContent(BootstraPagination);
    }
}

After that to pass the value as I assume to use dataset

<pagination data-nop="5" />

then the expected result should be bootstrap pagination with 5 number of pages nop

<nav><ul class='pagination'>
   <li class='page-item'><a class='page-link' href='0'>1</a></li>
   <li class='page-item'><a class='page-link' href='1'>2</a></li>
   <li class='page-item'><a class='page-link' href='2'>3</a></li>
   <li class='page-item'><a class='page-link' href='3'>4</a></li>
   <li class='page-item'><a class='page-link' href='4'>5</a></li>
</ul></nav>
2

There are 2 answers

0
MedoofromEgypt On

Finally, I got the solution for this!

to pass value from the custom tag helper to void Process I should use TagHelperContext context.

eg:

string nop = context.AllAttributes["nop"].Value.ToString();

if need int value just parse

int nop = int.Parse(context.AllAttributes["nop"].Value.ToString());

usage:

<pagination nop="5"></pagination>
0
Darkerone On

If you want to pass information through an attribute, define the attribute in your TagHelper (PascalCase) :

public int MyAttribute { get; set; }

And set it like that (kebab-case):

<pagination my-attribute="5"></pagination>

Attributes property in [HtmlTargetElement(Attributes = "pagination")] just define required attributes.