2011-07-25 61 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 
}