Validate Coupon code in asp.net by Calling WebMethod using javascript or jQuery


I need help to calculate resulted amount after applying coupon code, the thing is when user enter the coupon code, it can be of two type 0/1, suppose this is the table

Voucher Code

Amount

Off_type

Test

50

0

Demo

10

1

Now if the Off_type is 1, then Amount to be deducted should be as rupees, and if Off_type 0, then amount to be deducted should be percent of total.

For example: If total amount(without discount) is 100, and Coupon code is "Demo", then after discount total amount to be paid will be 90, as 100 - 10% Of (Total) =90

So I am not able to implement this functionality using jQuery and WebMethod, here is my current code

jQuery

function getcoupon()
    {

        $.ajax({
            type: "POST",
            url: "restaurant_menu.aspx/GetDetail",
            data: JSON.stringify({ coupon_code: $("#coupon_code").val() }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                if (data.d == "no") {
                   
                    
                    $("#btnnext").text("Proceed");
                    $("#btnnext").removeAttr("disabled", "disabled");
                    $("#coupon_code").val("");
                    $("#coupon_amount").val("0");
                    
                    $("#lblorderamount").text($("#total_amount_prepared").val());
                    $("#validate_coupon").html("Invalid Coupon!");
                    $("#btnnext").val("Proceed");
                }
                else {


              var total_amount = Math.round((parseFloat($("#total_amount_prepared").val()) - parseFloat(data.d)), 2);

                                        if (parseFloat($("#lblfamount").text()) >= parseFloat(data.d)) {
                        if (parseFloat($("#lblorderamount").text()) >= 300)
                        {
                            $("#lblfamount").text(total_amount);
                            $("#coupon_amount").val(data.d);
                            $("#btnnext").val("Proceed");
                            $("#btnnext").removeAttr("disabled", "disabled");
                            $("#validate_coupon").html("Coupon Verified Successfully!");
                        }
                        else
                        {
                            $("#coupon_code").val("");
                            $("#coupon_amount").val("0");

                            $("#lblfamount").text($("#total_amount_prepared").val());
                            
                            $("#btnnext").val("Proceed");
                            $("#btnnext").removeAttr("disabled", "disabled");
                            $("#validate_coupon").html("Coupon is only valid upto on minimum ? 300");
                        }
                        
                    }
                    else {
                        
                        $("#coupon_code").val("");
                        $("#coupon_amount").val("0");

                        $("#lblfamount").text($("#total_amount_prepared").val());


                        $("#btnnext").val("Proceed");
                        $("#btnnext").removeAttr("disabled", "disabled");
                        $("#validate_coupon").html("Coupon Amount is greater than Total Amount");
                    }


                }
            },
            failure: function (response) {
                alert("Failed");
            }
        });
    }
    var timer = null;
    function couponkeyup()
    {
        $("#btnnext").val("Loading....");
        $("#btnnext").attr("disabled", "disabled");
        $("#validate_coupon").html("");
        
        timer = setTimeout(getcoupon, 1000);
        
    }

C# Web Method

[System.Web.Services.WebMethod]
    public static string GetDetail(string coupon_code)
    {
       
        string s = "select voucher_amount from admin_voucher where voucher_code='" + coupon_code + "'";
        connect con = new connect();
        DataSet ds = con.get(s);
        if (ds.Tables.Count > 0)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                
                return Math.Round(Convert.ToDecimal(ds.Tables[0].Rows[0][0]), 2).ToString();
            }
            else
            {

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

Any help is appreciated, thanks


Asked by:- RameshwarLate
0
: 7452 At:- 2/8/2018 2:04:28 PM
C# ASP.NET Coupon code validation in ASP.NET Calling WebMethod using javascript Calling WebMethod using jQuery







1 Answers
profileImage Answered by:- vikas_jk

You need to send both Amount and off_type from C# webmethod then comapre if value is 1, get percent of total otherwise deduct amount from total amount(without) directly.

Suppose this is my sql table and data in it.

sql-table-deduct-coupon-code.png

Now my jQuery code to caculate coopon code will be

   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 != "No") {
                        //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);
        })

and C# web method will be as below

 [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 both 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 "No"; //means invalid coupon code
                    }
                }
                else
                {
                    return "No";
                }

            }
        }

As you can see i am returning both amount/Offtype in C# code, while in Ajax Success response I am splitting data using "-", as we know from C# code, 1st value will be Amount while 2nd value will be Off_type after splitting the string and then caculate total amount based on it.

Here is the demo output, based on above SQL table C#/jQuery Codeoutput-after-apply-coupon.png

Also explained it in this article https://qawithexperts.com/article/asp.net/calling-web-method-in-aspnet-from-jquery-ajax/96

2
At:- 2/9/2018 8:51:47 AM Updated at:- 2/10/2018 8:34:53 AM
Thank You 0
By : RameshwarLate - at :- 2/10/2018 11:55:23 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use