简体   繁体   中英

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');
}

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');
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM