我有一个 anchor 标签<a></a>
并通过 Jquery 我正在处理它的点击事件。onclick 我得到 x 和 y 位置,即 xIndex
和yIndex
分别。
我想将这两个值存储在数据库中,为此我有一个方法 StoreXY(string XIndex,string YIndex)
在 C# 后端 test.aspx.cs
文件 。但由于我在 javascript 变量中有 x 和 y 位置的值,我需要调用 StoreXY()
通过 JavaScript 的方法。以下是我正在使用的代码。
测试.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>
测试.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);
关于javascript - 无法在 asp.net 中通过 javascript 调用 C# 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29016486/