使用web-service返回的数据(jQuery,ASP.Net)

时间:2011-07-25 12:56:06

标签: jquery .net pagemethods

我有一个ASP.Net-Button,当点击它时,执行客户端和服务器端代码。 在某些条件下,应防止执行后者。

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

方法CheckItems调用Web服务。如果来自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;
            }
        });
    }

使用此代码,CheckItems不会返回false。怎么能实现这一目标?

网络方法:

[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();
        }
    }

1 个答案:

答案 0 :(得分:0)

由于您的javascript函数正在对服务器进行异步调用,因此它无法立即将结果返回给您的click事件。您需要将您的内容分成单独的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
}