Wednesday, August 12, 2009

Code: Prevent an asp:Button from doing a postback

<asp:Button ID="btnRunRecent" runat="server" Text="Generate" 
OnClientClick="RunMyMethod(); return false;" />

If you want to run a JavaScript method on a button click for a richer client experience you’ll need to add an attribute for OnClientClick to your asp:Button.  When it renders the actual html input tag to your web page it will add an onclick attribute and set your JavaScript to its value (onclick=”RunMyMethod(); return false;”)   Just place the name of your JavaScript method as the attribute value to allow the page to postback after running your script, if you don’t want the form to do a postback after finishing your script follow your method name with “return false;” as shown in the example.  If you don’t want any custom JavaScript function to run and just want to prevent the button from causing a postback just put “return false;” as the OnClientClick value.