Bohn Bohn - 3 months ago 7x
jQuery Question

Cancel button does not get called when ModelState is not valid

I had these two buttons:

<button id="submit" name="button" value="register" class="btn btn-primary">Submit</button>
<button id="cancel" name="button" value="cancel" class="btn btn-secondary">Cancel</button>

In a page that has some text fields with some validation on them for example

@Html.TextBoxFor(m => m.EmailRequest, new { @class = "form-control", type = "email" })
@Html.ValidationMessageFor(m => m.EmailRequest)

And then to know if cancel button was cliked to redirect them to some other page, in controller I had it like this:

public ActionResult ForgotPassword(string button, ForgotPasswordViewModel fpModel)
// cancel button, go back to LoginPage
if (!string.IsNullOrEmpty(button) && button == "cancel")
return RedirectToAction("Login");
// blah

It works if they fill out good valid values in the text boxes and then they click on cancel BUT it does not even get called when there are validation errors on the text boxes and then click cancel. So it won't redirect them either.

So what should i do ?


It sounds as if you are trying to POST the form back to the server in both scenarios (cancel or submit).

It doesn't make much sense to POST a form back to a server if there are validation issues. If you do this, you then rely on server side validation checking and make sure you re route to Login. You should always have server side, but it is obviously best to not just rely on it and to have both server side and client side validation.

An alternative solution would be to replace the cancel button with a link. E.g.

@Html.ActionLink("Cancel", "Login")

This is also quicker in terms of performance, because it will simply redirect the user to the login page. Instead of posting back to the server and then re routing.