![](/img/trans.png)
[英]Call a server side function from javascript in asp.net 2.0 without using script manager or pagemethods
[英]Call C# boolean function from Javascript code using PageMethods
好的,所以我有一個循環,可以制作按鈕並設置其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-ac-Method-63380306
改變你的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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.