0

In Razor pages ASP.NET Core, how do I do a basic onclick event for a button which is of type button?

Do I need to wire up an AJAX GET request to get the below "Resend Code" button to work? There is plenty of chatter about OnPost this and that.. but I don't want to post.

Can't be this hard?

<form method="post">
    <div asp-validation-summary="All"></div>

    <div class="form-group-item">
        <label asp-for="Input.TwoFactorCode"></label>
        <input asp-for="Input.TwoFactorCode" class="input" />
        <span asp-validation-for="Input.TwoFactorCode"></span>
    </div>

    <div class="form-group-item">
        <label class="margin-0" asp-for="Input.RememberMachine">
            <input asp-for="Input.RememberMachine" />
            @Html.DisplayNameFor(m => m.Input.RememberMachine)
        </label>
    </div>

    <div>
        <button type="button" asp-page-handler="ResendCode" class="btn btn-light">Resend Code</button>
        <button type="submit" class="btn btn-secondary">Confirm</button>
    </div>
</form>
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Andrew Duffy
  • 795
  • 2
  • 17
  • 37

3 Answers3

2

As it stands, the button won't do anything. You can use JavaScript to intercept the button click and then fire a get request using AJAX (jQuery example below):

$('.btn.btn-light').on('click', function(){
    $.get('?handler=ResendCode', data, function(){
        ...
    });
});
Mike Brind
  • 28,238
  • 6
  • 56
  • 88
0

You can try changing the button to use formmethod="get":

<button type="submit" formmethod="get" asp-page-handler="ResendCode" class="btn btn-light">Resend Code</button>

Note, this will only work for buttons that have type="submit" or type="image" (other type-values don't cause the form to submit). Also it's an HTML5 attribute.

Reference:

Peter B
  • 22,460
  • 5
  • 32
  • 69
0

maybe try making your own custom handler methods other than OnPost() and OnGet()

noob0349
  • 1
  • 3