Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call webmethod in Asp.net C#

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";
}

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

like image 664
Balwant Chaudhary Avatar asked Oct 01 '13 07:10

Balwant Chaudhary


People also ask

How do I call a WebMethod URL?

click(function () { var name = $('#name'). val(); /// alert("The btn was clicked."); jQuery. ajax({ url: 'test. aspx/GetData', type: "POST", dataType: "json", // data: "{'name': '" + name + "'}", contentType: "application/json; charset=utf-8", success: function (data) { alert(JSON.

How do you call webmethods?

you need to JSON. stringify the data parameter before sending it. Show activity on this post. 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.

How do you call a method inside WebMethod in C#?

As the WebMethod is static, it cannot call one normal method of the Page class. If you want to call one method inside the WebMethod, you need to mark it as Static.

How do you call ASPX WebMethod?

<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" /> </div>


1 Answers

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;
}
like image 195
JDandChips Avatar answered Oct 20 '22 21:10

JDandChips