好吧,所以我有一個循環,使按鈕和設置他們的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的名稱是名稱列或不是。
聽起來像是你需要使用Ajax。 – gunr2171