2011-07-25 28 views
1

我有一个ASP.Net-Button,点击后,它执行客户端和服务器端代码。 在某些情况下,应该防止后者的执行。使用web服务(jQuery,ASP.Net)返回的数据

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

请显示PageMethod'CheckItems' – naveen

回答

0

由于您的JavaScript函数向服务器的异步调用,它不能立即将结果返回给你的点击事件。你需要将你的东西分离成单独的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 
}