好吧,所以我有一个循环,使按钮和设置他们的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