Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you know which control is caused by postback?

All controls accept Button and ImageButton use JavaScript for causing a postback. To enable postback on these controls one has to set AutoPostBack property to true. When you set this property to true, __doPostBack function is called on event which causes a postback.

What is an ASP button?

asp:Button is an asp.net server control which fire an event on the server side. <input id="Submit1" type="submit" is a client side button of type submit, but it can act as a server side button as well by adding. runat="server" and onserverclick="eventname"


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" />

You can use jquery click action and use the preventDefault() function to avoid postback

<asp:button ID="btnMyButton" runat="server" Text="MyButton" />


$("#btnMyButton").click(function (e) {
// some actions here
 e.preventDefault();
}

Consider this.

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequest);
function BeginRequest(sender, e) {
    e.get_postBackElement().disabled = true;

}
     </script>

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!)