When you need to call ASP.NET WebMethod from front end, you can implement AJAX to call .NET code-behind methods.This solution allows you to create client-side JavaScript functions that retrieve data from the server via .NET web methods managed in the web form’s code-behind. So, In this article I will explain how to call WebMethod from jQUery Ajax with parameters in ASP.Net using C#.

First of all if you are new to AJAX, let's understand it using the below code with comments:

      $.ajax({
              type: "POST",                   // Type of Request, GET,POST, DELETE etc.
              url: "Default.aspx/GetDetail",   //URL which we need to call
              data: '{ coupon_code: '+$("#Name").val()+ '}', //paramter to pass
              contentType: "application/json; charset=utf-8", // dataType seding to server
              dataType: "json", // data returning from server
              success: function (data) { //function to call on success
                    //success, do something here using returned response
                    
              },
              failure: function (response) {
                    alert("Failed");
              }
           });

You can know more about contentType and dataType in jQuery

The above jQuery Ajax can be used when sometimes we need to stop annoying post-backs on ASP.NET Web Pages.Let's take a simple example, suppose you want to get Validate Coupon code in your .aspx page , so when user enters it and hit on button "Apply Coupon", you may need to verify if coupon is valid and if it valid how much discount to get.

So here are the steps, which i will follow :

1. Get Coupon code entered by user using jQuery on Button Click

2. Call Web method using Ajax and send coupon code to C# WebMethod in code behind.

3. Verify the coupon from database(With discount is is % or not) and if it is valid calculate the amount to be deducted.

Suppose this is my database table to verify coupon code:

sql-table-deduct-coupon-code.png

In the above table Off_type defines, the amount to deduct from Total amount would be in percent(if 1) or directly(0) in Currency(RS, $ etc)

Let's create the basic HTML for it, for which we need Total Amount of user, a Textbox to enter coupon code ,a button to verify, and total amount after coupon is applied.

 <input id="coupon_code" type="text" value="" />
    <input type="button" value="Apply Coupon" id="Apply_Coupon"/>
    <br/>
   Total Amount: <label id="TotalAmount">150</label> <br/>
   Total Amount after discount:  <label id="TotalAmountAfterDcisount"></label>

Now let's create a C# method to get data from database and verify the coupon code using WebMethod:

 [System.Web.Services.WebMethod]
        public static string GetDetail(string coupon_code)
        {
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = @"Server=DESKTOP-PC\SQLEXPRESS2;Database=DatabaseName;Trusted_Connection=true";
                string s = "select voucher_amount,Off_type from admin_voucher where voucher_code='" + coupon_code + "'";
               
                SqlDataAdapter da = new SqlDataAdapter();
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = s;
                da.SelectCommand = cmd;
                DataSet ds = new DataSet();

                conn.Open();
                da.Fill(ds);
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                       // return Amount and Off-Type
                        return Math.Round(Convert.ToDecimal(ds.Tables[0].Rows[0][0]), 2).ToString() + "-"+ ds.Tables[0].Rows[0][1].ToString();
                    }
                    else
                    {

                        return "Invalid"; //means invalid coupon code
                    }
                }
                else
                {
                    return "Invalid";
                }

            }
        }

So the jQuery Code to call Web Method, Check if response returned has discount type as percent ot not, and caculate and apply percent will be as below

<script type="text/javascript">
        function getcoupon() {

            $.ajax({
                type: "POST",
                url: "Default.aspx/GetDetail",
                data: JSON.stringify({ coupon_code: $("#coupon_code").val() }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    console.log(data.d);
                    //Check if Coupon is valid
                    if (data.d != "Invalid") {
                        //If valid split using '-'
                        var SplittedValues = data.d.split("-");
                        var total = $("#TotalAmount").text();
                        //check is coupon amount need to deduct in percent or not
                        if (SplittedValues[1] == "1") {
                            //yes percent
                           
                            var PercentTodeduct = SplittedValues[0];

                            var PercentOftotal = (parseFloat((PercentTodeduct / 100)) * parseFloat(total)); //calculate percent of total
                            console.log(PercentOftotal);
                            //deduct amount
                            $("#TotalAmountAfterDcisount").html(parseInt(total, 10) - parseInt(PercentOftotal, 10));
                        }
                        else {
                            // minus amount directly
                          
                            var AmountTodeduct = SplittedValues[0];

                              //deduct amount
                            $("#TotalAmountAfterDcisount").html(parseInt(total, 10) - parseInt(AmountTodeduct,10));
                        }
                    }
                    else {
                        //if "No" is sent, alert invalid coupun code
                        alert("Invalid coupon code");
                    }
                    
                },
                failure: function (response) {
                    alert("Failed");
                }
            });
        }

        $(document).ready(function () {

            $("#Apply_Coupon").on('click', getcoupon);
        })
   </script>

Now let's execute the above code and check it's working

Calling-WebMethod-using-jQUery-Ajax.gif

As you can see in the above-animated gif, when i entered  "TestDemo" code, 10% amount was deducted from total, when enerted "Invalid code", got an alert of invalid code and when entered "Test" as coupon code, amount was deducted directly from total.

That's it, so use the above jQuery Ajax way, we can easily call WebMethod using AJAX and without get data from the database without re-loading the web-page.