简体   繁体   English

使用网络服务返回的数据(jQuery,ASP.Net)

[英]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. 我有一个ASP.Net-Button,单击该按钮即可执行客户端和服务器端代码。 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. CheckItems方法调用Web服务。 If the response from the web-service is "DataFound", the method CheckItems should return false. 如果来自Web服务的响应为“ DataFound”,则CheckItems方法应返回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. 使用此代码,CheckItems不会返回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();
        }
    }

Since your javascript function is making an asynchronous call to the server, it cannot return the result immediately to your click event. 由于您的javascript函数正在异步调用服务器,因此它无法立即将结果返回到click事件。 You'll need to separate out your stuff into separate javascript functions, like: 您需要将自己的内容分成单独的javascript函数,例如:

<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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM