如何调用的webmethod在Asp.net C#webmethod、Asp、net

2023-09-10 16:47:51 作者:你送她回家却忘记我也怕黑

我想用下面的code调用在asp.net C#应用程序的Web方法

I want to call a web method in asp.net c# application using the following code

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#code:

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

但它始终调用的Page_Load。我该如何解决呢?

But it always call page_load. How can i fix it?

推荐答案

这是一个有点晚了,但我只是无意中发现了这个问题,试图解决我自己这样的问题。后来我意识到,我有这条线在阿贾克斯后错误的:

This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:

data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",

这应该是:

data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",

除了将WebMethod为:

As well as the WebMethod to:

public static string AddTo_Cart(string quantity, string itemId)

这解决了我的问题。

And this resolved my problem.

希望对大家有所帮助别人也是如此。

Hope it may be of help to someone else as well.