Question

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?

Was it helpful?

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
}

OTHER TIPS

Praveen's point (below, downvoted) about async or sync is really important here.

The "OnClientClick" answer will only work for synchronous stuff. If you have AJAX or a Promise, the best pattern I have found is:

1). Stop the default behavior of the button using javascript:

OnClientClick="return false;"

2). create a separate Javascript event handler for the button:

$(document).ready(function (e) {
            $("[id$='btn']").click(function(){ 

3). Call the client-side ASP validators (skip if you don't have any).

if (Page_ClientValidate())
            {

4). To the AJAX completion function, or in the promise.then() pass a function to submit the form triggering the button click event

__doPostBack('<%= btn.ClientID %>', 'OnClick');

Unless you are dealing with Promises or AJAX, that will all seem really convoluted.

Here is a full example page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="aaaaa_test.aspx.cs" Inherits="test" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script  type="text/javascript">

        $(document).ready(function (e) {

            //2). use the click event to capture the canceled submit.
            $("[id$='cmdSubmit']").click(function(){
                //3). Allow the asp client-side page validators to do their thing...
                if (Page_ClientValidate())
                {
                    ReturnsPromise().then(function () {
                        //4). once the Asynchronous stuff is done, re-trigger the postback
                        //    and make sure it gets handled by the proper server-side handler.
                        __doPostBack('<%= cmdSubmit.ClientID %>', 'OnClick');
                    });
                }
            });

            // very simple promise, usually this woud be an AJAXy thing.....
            //  a placeholder for your real promise.
            function ReturnsPromise()
            {
                //this is just a simple way to generate a promise for this example.
                return Promise.resolve($("[id$='hiddenField']").val($("[id$='txtInput']").val()));
            }

        });

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:HiddenField ID="hiddenField" runat="server" />
        Input:<asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="valInput" runat="server" ErrorMessage="Add Text" ControlToValidate="txtInput" EnableClientScript="True" Text="Add Text"></asp:RequiredFieldValidator>
        <br />
        <!-- 1). use client script to stop the default button behavior with OnClientClick="return false;" -->
        <asp:Button ID="cmdSubmit" runat="server" OnClick="cmdSubmit_Click" Text="Submit" OnClientClick="return false;" />

    </div>
    </form>
</body>
</html>
  1. First thing is your ajax call async or sync ? you will make ajax call using defer and promise concept

2, Create a hidden button, click the button from jquery after ajax call successful. and real button return false, so it will not perform postback.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top