'How to use anchor tag as submit button in asp.net razor pages

I have a handler method in razor page with name OnGetExpense(UsePayload payload)

page.cshtml:

<input type="hidden" asp-for="Filters.From" value="@Model.Filters.From.ToYYYYMMDD()" />
<input type="hidden" asp-for="Filters.To" value="@Model.Filters.To.ToYYYYMMDD()" />
<a asp-page-handler="Expense" class="btn btn-primary" type="button" style="border-color: inherit">
Expense
</a>

page.cshtml.cs:

public IActionResult OnGetExpense(UserPayload filter)
{
    Console.WriteLine(filter.From);
    Console.WriteLine(filter.To);
    return Page();
}

The From date and to date I am getting is 01-01-0001 it is not submitting the payload I needed.

Is there any tag attribute I can sen the payload with anchor tag?

Please help



Solution 1:[1]

Your rendered A tag will create a GET request to the endpoint, you need to to a POST to send the data in the body of the request and for the Controller to bind the Request Body to your UserPayload object.

To send the POST request you can either write some JavaScript and POST to JSON to the end point or wrap the code in a Form.

https://docs.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/4-working-with-forms

Your controller will need to have HttpPost attribute assigned.

[HttpPost]
public IActionResult OnGetExpense(UserPayload filter)
{
    Console.WriteLine(filter.From);
    Console.WriteLine(filter.To);
    return Page();
}

Solution 2:[2]

Is there any tag attribute I can sen the payload with anchor tag?

You can use asp-route-{value}

Below is a work demo, you can refer to it.

cshtml:

 <a  asp-page-handler="Expense" asp-route-attendeeid="12" class="btn btn-primary" type="button" style="border-color: inherit">Expense</a>

cshtml.cs

 public IActionResult OnGetExpense(int attendeeId)
        {
            return Page();
        }

result:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pi and Mash
Solution 2 Qing Guo