I am stuck at a small problem. I have this button within a form which already posts to a controller action method for example Edit(). Now I want have a cancel button which will post to a different action method for example Edit(int id). I am trying to override the default post as specified in the Html.Begin form so I attached a Javascript event but the event does not event hit. I know if I use a action link it works like a charm but then I have worry about making the link look like a button. Also I cannot place the link into a different form for the sake of physical placement with different elements in the form. Would truly appreciate any tips.
@using (Html.BeginForm("Edit", "RunLogEntry", FormMethod.Post, new { enctype = "multipart/form-data" })) {
<input id="create" class="art-button" type="submit" value="Save" />
<input id="cancel" class="art-button" type="submit" value="Cancel" />
}
$("#cancel").click(function(e) {
e.preventDefault(); //Keep form from posting
window.location.href = "REDIRECT URL";
});
Change the type of your
cancelbutton tobutton. This way, it won’t trigger the form submit by default. You’ll need to handle it with JavaScript.Also, in this case, you won’t need
e.preventDefault();line.