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

时间:2021-05-02 03:18:29

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

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

Jquery:

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:

C#代码:

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

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

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

8 个解决方案

#1


8  

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:

这有点晚了,但我偶然发现了这个问题,试图解决我自己的问题。然后我意识到我在ajax帖子中有这条线错了:

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

It should be:

它应该是:

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

As well as the WebMethod to:

以及WebMethod:

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.

希望它对其他人也有帮助。

#2


7  

There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.

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

Script example:

脚本示例:

$.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 example:

WebMethod示例:

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

#3


1  

I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.

我不确定为什么这不起作用,它在我的测试中工作正常。但这里有一种可能有用的替代技术。

Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.

不要在AJAX网址中调用该方法,只需使用页面.aspx网址,并将该方法作为参数添加到数据对象中。然后当它调用page_load时,您的数据将在Request.Form变量中。

jQuery

jQuery的

jQuery.ajax({
    url: 'AddToCart.aspx',
    type: "POST",
    data: {
        method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
    },
    dataType: "json",
    beforeSend: function () {
        alert("Start!!! ");
    },
    success: function (data) {
        alert("a");
    },
    failure: function (msg) { alert("Sorry!!! "); }
});

C# Page Load:

C#页面加载:

if (!Page.IsPostBack)
{
    if (Request.Form["method"] == "AddTo_Cart")
    {
        int q, id;
        int.TryParse(Request.Form["quantity"], out q);
        int.TryParse(Request.Form["itemId"], out id);
        AddTo_Cart(q,id);
    }
}

#4


0  

One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :

这里的一个问题是,当您从ajax调用传递字符串时,您的方法需要int值。如果需要,尝试将其更改为字符串并在web方法内部进行解析:

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

Edit : or Pass int parameters from ajax call.

编辑:或从ajax调用传递int参数。

#5


0  

The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..

问题出在[System.Web.Services.WebMethod],添加[WebMethod(EnableSession = false)],你可以摆脱页面生命周期,默认情况下,EnableSession在页面中为真,并使页面在生命周期中生效事件..

Please refer below page for more details http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx

有关详细信息,请参阅下面的页面http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx

#6


0  

JSON.stringify the data parameter before sending it.

在发送之前,JSON.stringify数据参数。

#7


0  

Necro'ing this Question ;)

Necro'ing这个问题;)

You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.

您需要将发送的数据更改为Stringified JSON,这样您就可以将Ajax调用模块化为单个可支持的函数。

First Step: Extract data construction

/***
 * This helper is used to call WebMethods from the page WebMethods.aspx
 * 
 * @method - String value; the name of the Web Method to execute
 * @data - JSON Object; the JSON structure data to pass, it will be Stringified
 *      before sending
 * @beforeSend - Function(xhr, sett)
 * @success - Function(data, status, xhr)
 * @error - Function(xhr, status, err)
 */
function AddToCartAjax(method, data, beforeSend, success, error) {
    $.ajax({
        url: 'AddToCart.aspx/', + method,
        data: JSON.stringify(data),
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        beforeSend: beforeSend,
        success: success,
        error: error
    })
}

Second Step: Generalize WebMethod

[WebMethod]
public static string AddTo_Cart ( object items ) {
    var js = new JavaScriptSerializer();
    var json = js.ConvertToType<Dictionary<string , int>>( items );

    SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);      
    return "Add";
}

Third Step: Call it where you need it

This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.

这可以在任何地方,JS文件,HTML文件或服务器端构造中调用。

var items = { "quantity": total_qty, "itemId": itemId };

AddToCartAjax("AddTo_Cart", items,
    function (xhr, sett) {  // @beforeSend
        alert("Start!!!");
    }, function (data, status, xhr) {   // @success
        alert("a");
    }, function(xhr, status, err){  // @error
        alert("Sorry!!!");
    });

#8


-1  

Here is your answer. use

这是你的答案。使用

                   jquery.json-2.2.min.js 
                      and
                   jquery-1.8.3.min.js

Javascript :

Javascript:

function CallAddToCart(eitemId, equantity) {
   var itemId = Number(eitemId);
   var quantity = equantity;
   var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
    $.ajax({
           url: "AddToCart.aspx/AddTo_Cart",
           type: "POST",
           dataType: "json",
           data: dataValue,
           contentType: "application/json; charset=utf-8",
           success: function (msg) {
                alert("Success");
           },
           error: function () { alert(arguments[2]); }      
        });
 }

and your C# web method should be

你的C#网络方法应该是

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
   SpiritsShared.ShoppingCart.AddItem(itemId, quantity);      
  return "Item Added Successfully";
}

From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.

从任何按钮单击或任何其他html控件事件,您可以使用参数调用javascript方法,该参数依次调用webmethod以获取json格式的值。

#1


8  

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:

这有点晚了,但我偶然发现了这个问题,试图解决我自己的问题。然后我意识到我在ajax帖子中有这条线错了:

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

It should be:

它应该是:

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

As well as the WebMethod to:

以及WebMethod:

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.

希望它对其他人也有帮助。

#2


7  

There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.

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

Script example:

脚本示例:

$.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 example:

WebMethod示例:

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

#3


1  

I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.

我不确定为什么这不起作用,它在我的测试中工作正常。但这里有一种可能有用的替代技术。

Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.

不要在AJAX网址中调用该方法,只需使用页面.aspx网址,并将该方法作为参数添加到数据对象中。然后当它调用page_load时,您的数据将在Request.Form变量中。

jQuery

jQuery的

jQuery.ajax({
    url: 'AddToCart.aspx',
    type: "POST",
    data: {
        method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
    },
    dataType: "json",
    beforeSend: function () {
        alert("Start!!! ");
    },
    success: function (data) {
        alert("a");
    },
    failure: function (msg) { alert("Sorry!!! "); }
});

C# Page Load:

C#页面加载:

if (!Page.IsPostBack)
{
    if (Request.Form["method"] == "AddTo_Cart")
    {
        int q, id;
        int.TryParse(Request.Form["quantity"], out q);
        int.TryParse(Request.Form["itemId"], out id);
        AddTo_Cart(q,id);
    }
}

#4


0  

One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :

这里的一个问题是,当您从ajax调用传递字符串时,您的方法需要int值。如果需要,尝试将其更改为字符串并在web方法内部进行解析:

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

Edit : or Pass int parameters from ajax call.

编辑:或从ajax调用传递int参数。

#5


0  

The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..

问题出在[System.Web.Services.WebMethod],添加[WebMethod(EnableSession = false)],你可以摆脱页面生命周期,默认情况下,EnableSession在页面中为真,并使页面在生命周期中生效事件..

Please refer below page for more details http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx

有关详细信息,请参阅下面的页面http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx

#6


0  

JSON.stringify the data parameter before sending it.

在发送之前,JSON.stringify数据参数。

#7


0  

Necro'ing this Question ;)

Necro'ing这个问题;)

You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.

您需要将发送的数据更改为Stringified JSON,这样您就可以将Ajax调用模块化为单个可支持的函数。

First Step: Extract data construction

/***
 * This helper is used to call WebMethods from the page WebMethods.aspx
 * 
 * @method - String value; the name of the Web Method to execute
 * @data - JSON Object; the JSON structure data to pass, it will be Stringified
 *      before sending
 * @beforeSend - Function(xhr, sett)
 * @success - Function(data, status, xhr)
 * @error - Function(xhr, status, err)
 */
function AddToCartAjax(method, data, beforeSend, success, error) {
    $.ajax({
        url: 'AddToCart.aspx/', + method,
        data: JSON.stringify(data),
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        beforeSend: beforeSend,
        success: success,
        error: error
    })
}

Second Step: Generalize WebMethod

[WebMethod]
public static string AddTo_Cart ( object items ) {
    var js = new JavaScriptSerializer();
    var json = js.ConvertToType<Dictionary<string , int>>( items );

    SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);      
    return "Add";
}

Third Step: Call it where you need it

This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.

这可以在任何地方,JS文件,HTML文件或服务器端构造中调用。

var items = { "quantity": total_qty, "itemId": itemId };

AddToCartAjax("AddTo_Cart", items,
    function (xhr, sett) {  // @beforeSend
        alert("Start!!!");
    }, function (data, status, xhr) {   // @success
        alert("a");
    }, function(xhr, status, err){  // @error
        alert("Sorry!!!");
    });

#8


-1  

Here is your answer. use

这是你的答案。使用

                   jquery.json-2.2.min.js 
                      and
                   jquery-1.8.3.min.js

Javascript :

Javascript:

function CallAddToCart(eitemId, equantity) {
   var itemId = Number(eitemId);
   var quantity = equantity;
   var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
    $.ajax({
           url: "AddToCart.aspx/AddTo_Cart",
           type: "POST",
           dataType: "json",
           data: dataValue,
           contentType: "application/json; charset=utf-8",
           success: function (msg) {
                alert("Success");
           },
           error: function () { alert(arguments[2]); }      
        });
 }

and your C# web method should be

你的C#网络方法应该是

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
   SpiritsShared.ShoppingCart.AddItem(itemId, quantity);      
  return "Item Added Successfully";
}

From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.

从任何按钮单击或任何其他html控件事件,您可以使用参数调用javascript方法,该参数依次调用webmethod以获取json格式的值。