Search code examples
c#htmlformsasp.net-corerazor-pages

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


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 class="card-body">
    <form method="post">

        <div class="form-group">
            <label class="control-label lead text-center" asp-for="GName">
                Enter A Name To Create Greetings
            </label>
            <div class="input-group">
                <div class="input-group-prepend">
                    <div class="input-group-text">
                        <i class="fa fa-file-signature fa-1x"></i>
                    </div>
                </div>
                <input required type="text" style="text-transform:uppercase" asp-for="GName" class="form-control" />

            </div>
        </div>
        <button type="button" class="btn btn-primary btn-block">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();
}

Solution

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

    <button type="submit" class="btn btn-primary btn-block">Create Greetings</button>
    

    Introduction to Razor Pages in ASP.NET Core