Search code examples
c#jqueryasp.net-3.5

Execute jQuery, then execute .NET


How do I get an asp:button to execute some jquery before it executes the .net code?

I basically have an asp:button, which has some jquery-ajax attached to it, and some .NET code. I've noticed that if the jquery is simply, like display an alert, everything works, but if the jquery is more complex, i.e. ajax where it has to go and connect to a database, it does not seem to work and it just executes the .NET.

I'm assuming this has got something to do with speed? That the .NET code starts before the jQuery script has finished?

So my question is, how do I set this up so when the asp:button is clicked, the jquery does it's thing, and once the jquery has finished, the .net part runs?


Solution

  • Try to use OnClientClick method, if you return false it will stop the postback.

    http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx

    <asp:Button id="btn" runat="server" OnClientClick="return onclick()" text="Click" />
    

    JavaScript:

    function onclick()
    {
       // do something
       return false; // this will stop the postback
    }