gpt4 book ai didi

c# - 如何在Asp.net C#中调用webmethod

转载 作者:可可西里 更新时间:2023-11-01 07:45:11 24 4
gpt4 key购买 nike

我想使用以下代码在 asp.net c# 应用程序中调用 web 方法

Jquery:

jQuery.ajax({
url: 'AddToCart.aspx/AddTo_Cart',
type: "POST",
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});

C#代码:

[System.Web.Services.WebMethod]
public static string AddTo_Cart(int quantity, int itemId)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}

但它总是调用 page_load。我该如何解决?

最佳答案

如果定义不正确,$.Ajax() 中有很多元素可能会导致问题。我建议以最基本的形式重写您的 javascript,您很可能会发现它工作正常。

脚本示例:

$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});

网络方法示例:

[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}

关于c# - 如何在Asp.net C#中调用webmethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19110170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com