[英]Not able to call a c# function through javascript in asp.net
我有一個錨標記<a></a>
並且通過Jquery我正在處理click事件。onclick我得到x和y的位置,分別是xIndex
和yIndex
。 我想將這兩個值存儲在數據庫中,為此我在c# test.aspx.cs
文件的后端有一個StoreXY(string XIndex,string YIndex)
方法。 但由於我在javascript變量中具有x和y位置的值,因此我需要通過javascript調用StoreXY()
方法。 以下是我正在使用的代碼。
test.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<a class="Build" href="#">Build</a>
<script>
$(document).ready(function () {
$(".Build").click(function () {
var r = parseInt($("#rows").val());
var c = parseInt($("#cols").val());
$(".outerDiv .isWalkable").each(function () {
var x1 = $(this).index();
var xIndex = (x1 % (c)) + 1;
var yIndex = Math.floor(x1 / c) + 1;
//calling c# function
PageMethods.StoreXY(xIndex,yIndex);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
//alert to just know that click event is actully handled
alert(xIndex + '-' + yIndex);
});
});
});
</script>
test.aspx.cs
[WebMethod]
public static string StoreXY(string Xindex, string Yindex)
{
SiteLogic SL = new SiteLogic();
Site ste = SL.SelectByID(Convert.ToInt32(HttpContext.Current.Request.QueryString["ID"]));
Walkable W = new Walkable();
W.X = Convert.ToInt32(Xindex);
W.Y = Convert.ToInt32(Yindex);
W.SiteID = ste.SiteID;
WalkableLogic wlc = new WalkableLogic();
int x= wlc.Insert(W);
if (x > 0)
return "Successfull";
else return "Unsuccessfull";
}
現在,我可以打印出x和y位置值來獲取警報,但是不會調用'test.aspx.cs'文件中的c#方法,因此不會在數據庫中插入任何條目。 如何從JavaScript調用“ StoreXY()”方法?
您需要在對Page方法的調用中包括成功和失敗函數:
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
PageMethods.StoreXY(xIndex,yIndex, onSuccess, onError);
//alert to just know that click event is actully handled
//May Fire before the above are complete.
alert(xIndex + '-' + yIndex);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.