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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19110170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:07:01  来源:igfitidea点击:

How to call webmethod in Asp.net C#

c#jqueryasp.netajaxwebmethod

提问by Balwant Chaudhary

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

我想使用以下代码在 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# 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。我该如何解决?

回答by Zaki

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 值。如有必要,尝试将其更改为字符串并在 webmethod 中解析:

[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 参数。

回答by Bryan

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 url 中调用方法,只需使用页面 .aspx url,并将方法作为参数添加到数据对象中。然后当它调用 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);
    }
}

回答by Chandan Kumar

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# web 方法应该是

[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 clickor any other html control eventyou can call to the javascriptmethod with the parameter which in turn calls to the webmethodto get the value in jsonformat.

从任何按钮click或任何其他 html 控件,event您可以调用javascript带有参数的方法,该方法又调用webmethod以获取json格式的值。

回答by JDandChips

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]
public static string TestMethod(string message)
{
     return "The message" + message;
}

回答by user3411833

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 为 true,并使页面通过生命周期事件进入生命周期。

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

回答by Karlth

you need to JSON.stringifythe data parameterbefore sending it.

你需要JSON.stringifydata parameter发送前。

回答by Fred

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.

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

回答by GoldBishop

Necro'ing this Question ;)

解决这个问题;)

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

您需要更改作为字符串化 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

[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!!!");
    });