好的,所以我有一个使按钮并设置其ID的循环,我想检查sql表中是否存在btn.id,然后将按钮颜色设置为红色(如果不存在),然后将按钮颜色设置为绿色那样简单。
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#函数“ Check”在下面,其中表名是“ Book”,并且该表具有一列“ Name”,因此,如果列名中存在一行,其名称是传递的值,则我希望此函数返回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);
}
}
但是问题是,每当我这样调用Check函数时
if (PageMethods.Check(btn.id) == true)
但这绝非事实,所有按钮的ID都是否为SQL表的“名称”列均设置为绿色。
最佳答案
您可以从JS调用c#代码,方法如下
http://code.msdn.microsoft.com/How-to-excecute-a-c-Method-63380306
关于c# - 使用PageMethods从Javascript代码调用C# bool 函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24562708/