Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
}
like image 853
mark smith Avatar asked Dec 16 '09 16:12

mark smith


2 Answers

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

like image 135
MikeTeeVee Avatar answered Oct 09 '22 07:10

MikeTeeVee


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');
}
like image 34
ilivewithian Avatar answered Oct 09 '22 08:10

ilivewithian