How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

Viewed 320408

I have an asp button. It's server-side so I can only show it for logged in users, but i want it to run a javascript function and it seems when it's runat="server" it always calls the postback event.

I also have a regular button (<input...>) not running at server and it works fine...

How can I make this button only run the javascript and not postback?

13 Answers

Have your javascript return false when it's done.

<asp:button runat="server".... OnClientClick="myfunction(); return false;" />
YourButton.Attributes.Add("onclick", "return false");

or

<asp:button runat="server" ... OnClientClick="return false" />

The others are right that you need your callback to return false; however I'd like to add that doing it by setting the onclick is an ugly old way of doing things. I'd recommend reading about unobtrusive javascript. Using a library like jQuery could make your life easier, and the HTML less coupled to your javascript (and jQuery's supported by Microsoft now!)

You don't say which version of the .NET framework you are using.

If you are using v2.0 or greater you could use the OnClientClick property to execute a Javascript function when the button's onclick event is raised.

All you have to do to prevent a server postback occuring is return false from the called JavaScript function.

You can use JQuery for this

<asp:Button runat="server" ID="btnID" />

than in JQuery

$("#btnID").click(function(e){e.preventDefault();})

You just need to return false from the

function jsFunction() {
  try {
    // Logic goes here
    return false; // true for postback and false for not postback
  } catch (e) {
    alert(e.message);
    return false;
  }
}
<asp:button runat="server" id="btnSubmit" OnClientClick="return jsFunction()" />

JavaScript function like below.

Note*: Always use try-catch blocks and return false from catch block to prevent incorrect calculation in javaScript function.

Related