How to submit a GET form in Razor Pages?

Viewed 21

I have a razor page that has a form. When the page first loads, it hits the default OnGet() handler. I also want to be able to submit the form on the page to a different OnGet handler, OnGetFormSubmit(), in which I can requery data to repopulate the page model properties and load the page again. The reason for splitting this is because I am refactoring and it should simplify logic in the page handlers.

To be clear, I don't want to use method="post" on the form because I'm not performing any action like deleting or updating a record - I'm just reloading the page with new data.

I think I could technically submit it to an OnPost() handler and then redirect to OnGetFormSubmit() with the submitted values, but the POST feels like a needless middleman.

I tried making a form with method="get" and specifying the page handler, but when I submit the form it hits the OnGet() handler and not OnGetFormSubmit().

From a design standpoint, does this make sense? How can I get it all to work?

HTML:

<form method="get" asp-page-handler="FormSubmit" >
   <input asp-for="Name" />

   <input type="submit" value="Submit" />
</form>

PageModel:

public class PersonModel : PageModel
{
    [BindProperty(SupportsGet = true)]
    public string Name { get; set; }

    public void OnGet()
    {
        // set up model
    }

    public void OnGetFormSubmit()
    {
        // set up model
    }
}

The rendered HTML form:

<form method="get" action="/Person?handler=FormSubmit">
    <input type="text" class="input-validation-error" data-val="true" data-val-required="The Name field is required." id="Name" name="Name" value="">

    <input type="submit" value="Submit">
</form>
1 Answers

I found the reason and solution in another thread (link).

From that solution:

When you submit a form using GET, the browser trashes query string values in the form action and replaces them with a new query string built from the form fields. You can hit your handler by adding an appropriate hidden field to the form:

In my case, the solution is to modify the HTML like so:

<form method="get">
   <input type="hidden" name="handler" value="FormSubmit" />

   <input asp-for="Name" />

   <input type="submit" value="Submit" />
</form>
Related