Somachr
Somachr

Reputation: 464

Razor page custom post method not firing

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.

Upvotes: 3

Views: 1644

Answers (3)

Mehdi
Mehdi

Reputation: 58

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>

Upvotes: 2

Somachr
Somachr

Reputation: 464

I have changed

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

for

<button ... />

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

Upvotes: 0

Yiyi You
Yiyi You

Reputation: 18159

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>

Upvotes: 1

Related Questions