mark smith
mark smith

Reputation: 20897

How do I stop a button event from posting in ASP.NET MVC?

I have a standard view and some standard input tags without runat=server:

<button id="submit">submit</button>
<button id="clear">clear</button>

Pressing either causes the page to submit. Instead, I want them to do nothing since I'm handling the click event with JQuery. How do I do this?

EDIT

Here is my jquery code

$('#submit').bind('click', submit_click);

function submit_click() {
    alert('clicked submit');
}

Upvotes: 16

Views: 14493

Answers (3)

MikeTeeVee
MikeTeeVee

Reputation: 19392

Set the type to button:

This will prevent the Form from Submitting.
No additional javascript functions necessary.
Note: When this property is not set, it will default to submit.

I assume your button Controls are inside a form tag or Html.BeginForm() code block.
Below are some Examples:

<button onclick="alert('You Clicked Implicit Submit.')">Implicit Submit</button>//Post Back Form.
<button onclick="alert('You Clicked Submit.')" type="submit">Submit</button>//Post Back Form.
<button onclick="alert('You Clicked Button.')" type="button">Button</button>//Stay on Client Page.

For a simple redirect (without Posting the Form back to its Default Action) you could also do this:

<button onclick="location.href='@Url.Action("Action", "Controller")'" type="button">Redirect</button>

Special thanks to the Answer found here: https://stackoverflow.com/a/17452739/555798

Upvotes: 15

ilivewithian
ilivewithian

Reputation: 19692

In your event handler you need to do:

$("button").click(function(event){
  event.preventDefault();
  // do something
});

taken from: http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29

update This should work in your code:

$('#submit').bind('click', submit_click);

function submit_click(event) {
    event.preventDefault();
    alert('clicked submit');
}

Upvotes: 8

Garry Shutler
Garry Shutler

Reputation: 32698

Add this to your click event bindings:

$('#submit').bind('click', submit_click);

function submit_click() {
    alert('clicked submit');
    return false;
}

Returning false stops the regular behaviour of the button happening, instead only performing your code.

Upvotes: 3

Related Questions