Razor page custom post method not firing

Viewed 524

Why this:

<form method="post">
  <nav>
   <ul class="pagination justify-content-center">
    <li class="page-item">
      <a class="page-link" asp-page-handler="filter" asp-route-id="1">1</a>
    </li>
   </ul>
  </nav>
 </form>

Does not fire OnPostFilter method inside backend?

public void OnGet()
    {
        ProdGoal = 15000;
        FillChart();
    }

    public void OnPostFilter(string id)
    {
        int MonthNum;
        if (int.TryParse(id, out MonthNum) && MonthNum >= 1 && MonthNum <= 12)
            FillChart(MonthNum);
        else
            FillChart();
    }

It always fires OnGet(). But when I would move the tag in front of it would work. Why is that? How should I make fire Post method.

3 Answers

It is because the request method is get when you click <a class="page-link" asp-page-handler="filter" asp-route-id="1">1</a>,so you cannot go to post handler.

1.You can try to change the handler name to OnGetFilter:

public void OnGetFilter(string id)
    {
        int MonthNum;
        if (int.TryParse(id, out MonthNum) && MonthNum >= 1 && MonthNum <= 12)
            FillChart(MonthNum);
        else
            FillChart();
    }

2.If you don't want to change the handler name,try to change your html:

<form method="post" asp-page-handler="filter" asp-route-id="1">
    <nav>
        <ul class="pagination justify-content-center">
            <li class="page-item">
                <input type="submit" value="1"/>
            </li>
        </ul>
    </nav>
</form>

This is because tag a always creates an HTTPRequest of Get Type and by click on the generated link, does not send information to the server by form tag. If you want to call the OnPostFilter Handler, you must create a HTTPRequest of Post Type. For creation Post HTTPRequest, you must create a submit element in Form Tag.

<form method="post">
    <nav>
        <ul class="pagination justify-content-center">
            <li class="page-item">
                <button class="page-link" asp-page-handler="filter" asp-route-id="1">1</button>
            </li>
        </ul>
    </nav>
</form>

or

<form method="post">
    <nav>
        <ul class="pagination justify-content-center">
            <li class="page-item">
                <input type="submit" class="page-link" asp-page-handler="filter" asp-route-id="1" value="1" />
            </li>
        </ul>
    </nav>
</form>

I have changed

<input type="submit" value="1"/>

for

<button ... />

Now it works but I still don´t know why input is firing OnGet()

Related