Home > Enterprise >  Button click not hitting OnPost() method when ENTER is hit
Button click not hitting OnPost() method when ENTER is hit

Time:12-20

I'm implementing a Form on ASP.NET Core Razor Page. The problem is OnPost() method is being hit on enter keypress (That is Only when we first click on GName Input field and the cursor start blinking and then we press Enter) and not hitting on button click.

Here is the .cshtml file <Form> code:

<div >
    <form method="post">

        <div >
            <label  asp-for="GName">
                Enter A Name To Create Greetings
            </label>
            <div >
                <div >
                    <div >
                        <i ></i>
                    </div>
                </div>
                <input required type="text" style="text-transform:uppercase" asp-for="GName"  />

            </div>
        </div>
        <button type="button" >Create Greetings</button>
    </form>
</div>

Here is the OnPost() method from PageModel:

[BindProperty]
public string GName { get; set; }
 
public IActionResult OnPost()
{
    return GName != null ? RedirectToPage("./SelectGreetings", new { gname = GName }) : (IActionResult)Page();
}

CodePudding user response:

Change the button type to submit to perform the form submission:

<button type="submit" >Create Greetings</button>

Introduction to Razor Pages in ASP.NET Core

  • Related