Search code examples
jquery.netpagemethods

Use data returned by web-service (jQuery, ASP.Net)


I have an ASP.Net-Button which, when clicked, executes client side and server side code. Under certain conditions, the execution of the latter should be prevented.

<asp:LinkButton OnClientClick="if(CheckItems() == false) return false;" runat="server" 
       ID="Button" onclick="Button_Click">Insert</asp:LinkButton>

The method CheckItems calls a web-service. If the response from the web-service is "DataFound", the method CheckItems should return false.

function CheckItems() {

        PageMethods.CheckItems($('#<%= txtField.ClientID  %>').val(), function(response) {

            if (response == "DataFound") {
                alert("The text you entered does already exist.");
                return false;
            }
        });
    }

With this code, CheckItems does not return false. How can this be achieved?

The web-method:

[WebMethod]
    public static string CheckItems(string name)
    {
        SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CS"].ConnectionString);

        try
        {
            conn.Open();

            var selectCommand = conn.CreateCommand();

            selectCommand.CommandText = @"SELECT COUNT(*) FROM [Table] WHERE Name = @Name";
            selectCommand.Parameters.Add(new SqlParameter("Name", name));

            int results = (int)selectCommand.ExecuteScalar();

            if (results > 0)
                return "DataFound";
            else
                return "NoDataFound";
        }
        finally
        {
            conn.Close();
        }
    }

Solution

  • Since your javascript function is making an asynchronous call to the server, it cannot return the result immediately to your click event. You'll need to separate out your stuff into separate javascript functions, like:

    <a onclick="buttonClicked();">Insert</a>
    
    function buttonClicked() {
        PageMethods.CheckItems($('#<%= txtField.ClientID  %>').val(), function(response) {
            if (response == "DataFound") {
                alert("The text you entered does already exist.");
            } else {
                performPostback();
            }
        });
    }
    
    function performPostback() {
        // Actually do your form post, maybe using __doPostBack
    }