Friday 22 September 2023

Cart Management | C# ASP.Net MVC

 




Cart Management | C# ASP.Net MVC

cart management is the most important part of the E-commerce website design. There are many ways to achieve it but Session is one of the simplest method. This post help you to learn, How to implement a shopping cart using  Session  in C# ASP.Net MVC Pattern from scratch. 






Step 1 Model



public class CartModel
{
        public string CID { get; set; }
        public List<CartProductModel> Cart { get; set; }
        public string Total { get; set; }
        public string UID { get; set; }
        public string Discount { get; set; }
}
public class CartProductModel
{
        public string ID { get; set; }
        public string ProductID { get; set; }
        public string ProductName { get; set; }
        public string Price { get; set; }
        public string Qty { get; set; }      
}

CartModel is main class which will save the products in cart using CartProductModel class with User ID, Total Amount and Discount. CartProductModel class will save a single product when user add an item in class then add this product in generic list in CartModel class Cart object.

Step 2 Add to Cart





In this sample, I have create Product shop or Single Product page flat in HTML Page. You can modify it as per your code. Normally this section renders dynamically based on data coming from database.

I have created a function AddtoCart() in cart.js. This function call by add to button click.Argument will bind while on click event on Add to cart button. The signature of function is given below 

function AddtoCart(pid, pname, price, proqty)
{
    FlagSID = true;
    var Lecob =
    {
        ProductID: pid,
        ProductName: pname,
        Price: price,
        Qty: $("#" + proqty).val()
    }

    $.ajax({
        url: '/Home/AddToCart/',
        dataType: "json",
        async: false,
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(Lecob),
        success: function (data) 
        {
            if (data.sMessage == "1"
            {
                window.location.href = "/Home/cart";
            }
            else 
            {
                alert(data.sMessage);
            }
        }
    });
}

Controller JSON function 

public JsonResult AddToCart(CartProductModel product)
{
            if (Session["Cart"] == null // When cart is null
            {
                CartModel ob = new CartModel();
                Random r = new Random();
                ob.Cart = new List<CartProductModel>();
                ob.CID = r.Next(1, 100).ToString();
                ob.Cart.Add(SetCartProduct(product.ProductID, product.ProductName, product.Price, product.Qty));
                ob.Total = product.Price;
                Session["Cart"] = ob;
                return Json(new { sMessage = "1", JsonRequestBehavior.AllowGet });
            }
            else
            {

                 //if cart have item
                 // Read cart from session and store into Cart model object                                      CartModel OldCart = (CartModel)Session["Cart"];
                  // Get all products from cart into product model                                               List<CartProductModel> data = ((CartModel)Session["Cart"]).Cart;                                 var index = data.FindIndex(e => e.ProductID == product.ProductID);                          // find current product is exist in cart
                if (index == -1) // product is not exist in cart
                {

                    OldCart.Cart.Add(SetCartProduct(product.ProductID, product.ProductName, product.Price, product.Qty));
                    Session["Cart"] = OldCart;
                    OldCart.Total = Convert.ToString(Convert.ToInt32(OldCart.Total) + (Convert.ToInt32(product.Price) * Convert.ToInt32(product.Qty)));
                    return Json(new { sMessage = "1", JsonRequestBehavior.AllowGet });

                }
                else //if product is exist in cart
                { 

                    int oqty = 0;
                    oqty = Convert.ToInt32(data[index].Qty);
                    oqty += Convert.ToInt32(product.Qty);
                    data[index].Qty = oqty.ToString();
                    return Json(new { sMessage = "1", JsonRequestBehavior.AllowGet });                          }  

            }

        }

 // Add an item into cart

protected CartProductModel SetCartProduct(string id, string name, string price, string qty)
{

            CartProductModel ob = new CartProductModel();
            ob.ProductID = id;
            ob.ProductName = name;
            ob.Price = price;
            ob.Qty = qty;          
            return ob;
 }


Show Products

HTML

<img src="~/img/100.jpg" />
<br /><br />
<strong>PID : </strong> 100 <br />
<strong>Maharaza Chair</strong<br />
<strong>Price : </strong>  123  <br />
<strong>Qty : </strong><input type="number" value="1" min="1" max="10" id="q100">
<br /><br />
<a href="/home/product?pid=100&nm=Maharaza Chair&price=123">
   <input type="button" value="View Product" class="btn btn-success" />
</a>
<input type="button" value="Add to Cart" class="btn btn-primary" onclick="AddtoCart('100','Maharaza Chair','123','q100')" />

I have shown static values for product details. you can implement your login because, in a real environment, these values come from the database and render using a loop

Show a single product

HTML

<div class="row">
  <div class="col-md-6">
     <img src="@string.Concat("/img/",Request.QueryString["pid"],".jpg")"  />
   </div>
  <div class="col-md-6">
     <h1>@Request.QueryString["nm"]</h1><hr />
     <strong>Price : </strong> @Request.QueryString["price"] <br /><br />
     <input type="number" value="1" min="1" max="10" id="qty"><br /><br />
     <input type="button" value="Add to Cart" class="btn btn-primary" onclick="AddtoCart('@Request.QueryString["pid"]','@Request.QueryString["nm"]','@Request.QueryString["price"]', 'qty')" />
    </div>
/div>


I have shown product details using query string because I want to make this post simple and short. You can change these HTML as per your theme because in the real world product details will come from the database.

Step 3 Modify Cart


HTML


<input type="number" value="@item.Qty" style="width:50px" id="@string.Concat("qty",item.ProductID)" onchange="ChangeCount('@item.ProductID','@item.ProductName','@item.Price','@string.Concat("qty",item.ProductID)','@string.Concat("qty",item.ProductID)');ProductAlter('@string.Concat("price",item.ProductID)','@string.Concat("qty",item.ProductID)', '@string.Concat("tot",item.ProductID)')" />

Cart item count control ID is created using product ID with qty prefix to make a unique ID for every cart count change control. This ID will pass to the function to read the item number entered by the user.

Javascript Function

function ChangeCount(pid, productname, price, qty)
{

    if (parseInt($("#" + qty).val()) > 0)
   {
          

        window.location.href = "/home/ChangeCartCount?pid=" + pid + "&name=" + productname + "&price=" + price + "&qty=" + $("#" + qty).val();    

    }
    else
    {
        alert("0 Quantity is not allowed.")
        $("#" + qty).val('1');

    }

}

Json function ChangeCartCount on Home controller to handle cart modification request

public ActionResult ChangeCartCount(string pid, string name, string price, string qty)
{
    CartModel OldCart = (CartModel)Session["Cart"];
    List<CartProductModel> data = ((CartModel)Session["Cart"]).Cart;
    int oqty, oprice, ototal;
    var index = data.FindIndex(e => e.ProductID == pid);
    oqty = Convert.ToInt32(data[index].Qty);
    oprice = Convert.ToInt32(data[index].Price);
    ototal = Convert.ToInt32(OldCart.Total);
    ototal = ototal - (oqty * oprice);
    ototal += Convert.ToInt32(qty) * Convert.ToInt32(price);
    OldCart.Total = ototal.ToString();
    data[index].Price = price;
    data[index].Qty = qty;
    return RedirectToAction("cart", "home");
 }

Step 4 (Delete an item from cart)

HTML

<a href="/home/DelCartItem?pid=@item.ProductID" onclick="return confirm('Are you sure to delete this product')">
     <input type="button" value="Delete" class="btn-danger btn" />                              </a>

Json function DelCartItem on Home controller to delete an item from cart. 

public ActionResult DelCartItem(string pid)
{
   List<CartProductModel> data = ((CartModel)Session["Cart"]).Cart;
   string tot = data.ElementAt(data.FindIndex(e => e.ProductID == pid)).Price;                     string qty = data.ElementAt(data.FindIndex(e => e.ProductID == pid)).Qty;              data.RemoveAt(data.FindIndex(e => e.ProductID == pid));
   if (data.Count == 0) // when only item in cart

   {
       Session["Cart"] = null;
   }
   else
   {
       CartModel OldCart = (CartModel)Session["Cart"];
       Session["Cart"] = OldCart;
       OldCart.Total = Convert.ToString(Convert.ToInt32(OldCart.Total) - (Convert.ToInt32(tot) * Convert.ToInt32(qty)));
    }
    return RedirectToAction("cart", "home");
 }

No comments:

Post a Comment