2014-07-03 42 views
0

好吧,所以我有一個循環,使按鈕和設置他們的ID,我想檢查如果btn.id存在於SQL表中然後設置按鈕顏色紅色,如果不是然後設置按鈕顏色綠色簡單。使用PageMethods從Javascript代碼調用C#布爾函數

function InIT() { 
      for (i = 1; i <= 10; i++) { 

       var btn = document.createElement("BUTTON"); 

       btn.id = i ;      
       btn.style.cssText = 'height:50px;width:50px;margin:5px;'; 
       if (PageMethods.Check(btn.id) == true)          
       { 
        btn.style.cssText = 'background:red;height:50px;width:50px;margin:5px;'; 
       } 
       else 
       { 
        btn.style.cssText = 'background:green;height:50px;width:50px;margin:5px;'; 
       } 

       document.getElementById("div1").appendChild(btn); 
       //this is a div where i create the buttons 


} 

現在的C#功能「查詢」是下面的其中表的名字是「尚書」,這表有一名欄「姓名」,所以我想這個功能,如果在列名在存在行返回true它的名字是傳入的值「ID」。

[System.Web.Services.WebMethod] 
     public static bool Check(string ID) 
     { 
      string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"].ToString(); 
      using (SqlConnection con = new SqlConnection(connectionString)) 
      using (SqlCommand cmd = new SqlCommand(@" 
         IF EXISTS(SELECT 1 FROM Book Where Name = @ID) 
         SELECT 1 ELSE SELECT 0", con)) 
      { 
       con.Open(); 
       cmd.Parameters.AddWithValue("@ID", ID); 
       int result = Convert.ToInt32(cmd.ExecuteScalar()); 
       return (result == 1); 
      } 
     } 

但問題是,每當我這樣調用

if (PageMethods.Check(btn.id) == true) 

檢查功能但這是不正確的,所有按鈕都設置爲綠色不管它們的ID的名稱是名稱列或不是。

+0

聽起來像是你需要使用Ajax。 – gunr2171

回答

0

改變你的JavaScript函數來此

<script type="text/javascript"> 
     var btn; 
     function InIT() { 
      debugger; 
      for (var i = 1; i <= 10; i++) { 

       btn = document.createElement("BUTTON"); 

       btn.id = i; 
       btn.style.cssText = 'height:50px;width:50px;margin:5px;'; 
       PageMethods.Check(btn.id, OnSuccess, OnFailure); 

      } 
     } 

     function OnSuccess(data) { 
      debugger; 
      if (data) { 
       btn.style.cssText = 'background:red;height:50px;width:50px;margin:5px;'; 
      } 
      else { 
       btn.style.cssText = 'background:green;height:50px;width:50px;margin:5px;'; 
      } 

      document.getElementById("div1").appendChild(btn); 
     } 

     function OnFailure() { 
      alert('Error'); 
     } 

    </script> 
+0

更改爲此,它不會提醒我'錯誤',所以我想它可以正常工作,我想函數調用OnSuccess但按鈕保持無色,所以也不紅色或綠色。 –

+0

運行在Internet Explorer中的解決方案調試器上的功能(如上面的代碼所寫)將被調用,你可以檢查出現了什麼問題 –

+0

我添加了'alert('Success');'OnSuccess函數並且它不提示所以我想'PageMethods.Check(btn.id,OnSuccess,OnFailure);'似乎不能正常工作 –

相關問題