Tuesday, September 16, 2014

Ajax based Shopping cart example in jquery Asp.net

In this example we have show basic functionally of shopping cart using ajax. So we have three classes  named  shopping cart, shopping cart model, product. Product class contain the three propertiesproductId, productname, unitprice as shown given below
public class Product
{
    public int ProductId { getset; }
    public string ProductName { getset; }
    public decimal UnitPrice { getset; }
}
Here shopping class contain the info  productid, productname ,quantity , unitprice, total price . TheseInfo store in shopping cart class
public class ShoppingCart
{
    public int ProductId { getset; }
    public string ProductName { getset; }
    public int Quantity { getset; }
    public decimal UnitPrice { getset; }
    public decimal TotalPrice { getset; }


}

Third class in contain the contain the info Alltoatal, vat price to show the sholoping cart is given below

public class ShoppingCartModel
{
    public ShoppingCartModel()
    {
        _shoppingCartItem = new List<ShoppingCart>();
    }
    public decimal AllTotal { getset; }
    public decimal AllTotalWithVat { getset; }
    public List<ShoppingCart> _shoppingCartItem { getset; }

}


Aspx.cs file : I have store the shoping cart item in session  in this example

const decimal _vat = 12.5M;//vat calculation
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["ShoppingCart"] = new ShoppingCartModel();
            bindData();
        }
    }
//Bind the product and  display in repeater
    public void bindData()
    {
        List<Product> data = new List<Product>{
            new Product    {ProductId=1,ProductName="Toy",UnitPrice=18.4M },
            new Product{ProductId=2,ProductName ="Chile rice", UnitPrice=12.5m},
              new Product{ProductId=3,ProductName ="Chawmin", UnitPrice=23.5m}
       
        
        };

        Repeater1.DataSource = data;
        Repeater1.DataBind();
    }

//Add/update item in cart

    [WebMethod(true)]
    public static ShoppingCartModel AddProduct(int ProductId, string ProductName, stringUnitPrice)
    {
        var shoppingModel = (ShoppingCartModel)HttpContext.Current.Session["ShoppingCart"];
        var shoppingCartItems = shoppingModel._shoppingCartItem;
        var ItemUpdate = shoppingCartItems.Where(d => d.ProductId == ProductId).FirstOrDefault();
        if (ItemUpdate != null) { ItemUpdate.Quantity = ItemUpdate.Quantity + 1; ItemUpdate.TotalPrice = ItemUpdate.Quantity * ItemUpdate.UnitPrice; }
        else
            shoppingCartItems.Add(new ShoppingCart { ProductId = ProductId, ProductName = ProductName, Quantity = 1, UnitPrice = Convert.ToDecimal(UnitPrice), TotalPrice =Convert.ToDecimal(UnitPrice) });


        shoppingModel._shoppingCartItem = shoppingCartItems;
        shoppingModel.AllTotal = shoppingCartItems.Sum(p => p.TotalPrice);
        shoppingModel.AllTotalWithVat = shoppingCartItems.Sum(p => p.TotalPrice) * _vat / 100 + shoppingCartItems.Sum(p => p.TotalPrice);
        HttpContext.Current.Session["ShoppingCart"] = shoppingModel;

        return shoppingModel;
    }
//remove item in cart


    [WebMethod(true)]
    public static ShoppingCartModel DelProduct(int ProductId)
    {
        var shoppingModel = (ShoppingCartModel)HttpContext.Current.Session["ShoppingCart"];
        var shoppingCartItems = shoppingModel._shoppingCartItem;
        var ItemUpdate = shoppingCartItems.Where(d => d.ProductId == ProductId).FirstOrDefault();
        shoppingCartItems.Remove(ItemUpdate);

        shoppingModel._shoppingCartItem = shoppingCartItems;
        shoppingModel.AllTotal = shoppingCartItems.Sum(p => p.TotalPrice);
        shoppingModel.AllTotalWithVat = shoppingCartItems.Sum(p => p.TotalPrice) * _vat / 100 + shoppingCartItems.Sum(p => p.TotalPrice);
        HttpContext.Current.Session["ShoppingCart"] = shoppingModel;

        return shoppingModel;
    }
}//DelProduct

//aspx Page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="scripts/jquery-1.7.2.js"></script>
    <%-- <script src="scripts/knockout-3.1.0.js"></script>--%>
    <script type="text/javascript">

        $(function () {
//Add item in cart
            $(".add").click(function () {
                // alert("hello");
                var ProductId = $(this).attr("data-val");
                var ProductName = $(this).attr("data-val1");
                var UnitPrice = $(this).attr("data-val2");
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/AddProduct",
                    data: '{ProductId: "' + ProductId + '",ProductName:"' + ProductName +'", UnitPrice:"' + UnitPrice + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (response) {
                        alert(response.d);
                    }
                });


            });
//Remove item in cart
            $(".del").live('click'function () {

                var ProductId = $(this).attr("data-val");

                $.ajax({
                    type: "POST",
                    url: "Default.aspx/DelProduct",
                    data: '{ProductId: "' + ProductId + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (response) {
                        alert(response.d);
                    }
                });
            });


        });

        function OnSuccess(response) {
            var ShoppingBody = "<table border=1>";
            $.each(response.d._shoppingCartItem, function (index, data) {
                ShoppingBody += "<tr> <td> " + data.ProductName + "</td> <td>" + data.Quantity + " </td> <td>" + data.UnitPrice + " </td> <td> " + data.TotalPrice + "</td><td> <a class='del' href='javascript:void' data-val=" + data.ProductId + ">X</a> </td></tr>";

            })
            ShoppingBody += "</table>";
            $("#Items").html("");
            $("#Items").html(ShoppingBody);
            $("#totalPrice").html("");
            $("#GrandTotal").html("");
            $("#totalPrice").html(response.d.AllTotal);
            $("#GrandTotal").html(response.d.AllTotalWithVat);
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">

        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <div id="items_<%#Eval("ProductId") %>"><%#Eval("ProductName") %> <span><%#Eval("UnitPrice").ToString() %> </span><a class="add" href="javascript:void" data-val="<%#Eval("ProductId") %>" data-val1="<%#Eval("ProductName") %>" data-val2="<%#Eval("UnitPrice").ToString() %>">Add To Cart</a> </div>

            </ItemTemplate>

        </asp:Repeater>
        <div>
        </div>


        <div id="shopping Cart" style="position: fixed; bottom: 0px; margin-bottom: 20px;margin-left: 25px;">
            <h1>Cart: </h1>
            <div id="Items"></div>
            Total Price:
            <div id="totalPrice"></div>
            Grand Total :
            <div id="GrandTotal"></div>
            (12.5% vat Included)
           

        </div>
    </form>
</body>
</html>
So it is basic ajax shopping cart using jquery in asp.net.


No comments:

Post a Comment

http://blogsiteslist.com