javascriptc#asp.netonclientclick

Running Server Method after Client Javascript Method


Is it possible to setup an asp button so that when it is clicked, the client-side javascript will run, and then the server-side c# method will run, but only after the prior javascript has completed? The goal being when the client submits a form, the 3rd-party jscript does its thing and sends out the form data. When that is done, the server-side method will run, create the file it needs to, and then post it back so that the client can download it. I have both of these working separately, but trying to put them together has been the issue.

Doing some google-fu and S.O. searching has led me to think that maybe the option would be having OnClientClick and OnServerClick attached to the same asp:button? Or is there a different way?


Solution

  • You just need to provide the javascript method for OnClientClick. It will be executed before the postback takes place. You can even prevent it by returning false:

    function JsMethodName() {
        // do something...
        // return true; // postback
        // return false; // no postback
    }
    
    <asp:Button ID="ButtonID" 
        OnClientClick="return JsMethodName();" 
        OnClick="ServerMethod" runat="server" Text="ButtonText" />