Home > Enterprise >  onget handler razor pages
onget handler razor pages

Time:01-20

I have a button on a GET Form on asp.net core razor pages

<form method="get" asp-page="Index">
<button type="submit" asp-page="Index" asp-page-handler="Something" ></button>
</form>

and the code behind

public IActionResult OnGetSomething(){
//... some code
return Page();
}

My problem is the onget handler code is never executed If the form is POST the onpost handler will work fine but if it is GET it doesn’t work

So what am I missing here? and how to make the onget handler work?

CodePudding user response:

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:

<form method="get" asp-page="Index">
    <input type="hidden" name="handler" value="Something" />
    <button type="submit" >Get</button>
</form>

CodePudding user response:

you can't go to get method because of parameters miss matching. Suppose:

In controller

    [HttpGet]
  public IActionResult Create()
        {
            return View();
        }
//Post Method
[HttpPost]
[ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(string Name)
        {
        }

In View:

<form asp-action="Create">
            <div asp-validation-summary="ModelOnly" ></div>
            <div >
                <label asp-for="Name" ></label>
                <input asp-for="Name"  />
                <span asp-validation-for="Name" ></span>
            </div>]

            <div >
                <input type="submit" value="Create"  />
            </div>
        </form>

Then it go post method cause it has 1 parameters (Name). if we not net any input or parameters are not same then it hit different method.

It the concept of method overloading

In details of method overloading https://www.geeksforgeeks.org/c-sharp-method-overloading/

  •  Tags:  
  • Related