How to call webmethod in Asp.net C#
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.
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;}
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 + "}",
It should be:
data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",
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.
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.
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.
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!!!"); });