2014-07-03 41 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);'似乎不能正常工作 –

相关问题