This Tutorial will show how to create shopping cart in MVC using Jquery and Ajax.
In previous artilce I have shown How to create login and Registration page in MVC
Step 1- Create a new Empty MVC project.
Step 2- Add the following class to your model folder.
public class Item
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
public string Description { get; set; }
public string Category { get; set; }
public int Offer { get; set; }
public string ImagePath { get; set; }
}
public class Cart
{
[Key]
public int Id { get; set; }
public string UserName { get; set; }
public int ItemId { get; set; }
}
public class Login
{
[Key]
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
Step 3- Add Context Class.
using System.Data.Entity;
namespace ShopingCartDemo.Models
{
public class DemoContext : DbContext
{
public DbSet<Item> Item { get; set; }
public DbSet<Cart> Cart { get; set; }
public DbSet<Login> Login { get; set; }
}
}
Step 4- Build your solution then add Home Controller . Here I have Created Login page . To know more about how to create login page see previous artilcel. Create Login Page In MVC
Step 5- Add the following code to your Controller .
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ShopingCartDemo.Models;
namespace ShopingCartDemo.Controllers
{
public class HomeController : Controller
{
DemoContext dbObj = new DemoContext();
public ActionResult Index()
{
if (Session["username"] == null)
{
return RedirectToAction("login");
}
else
{
string getName = Session["username"].ToString();
ViewBag.userName = getName;
int count = dbObj.Cart.Where(s => s.UserName == getName).Count();
ViewBag.cartCount = count;
return View("Index", getAllItems());
}
}
[HttpGet]
public ActionResult Login()
{
Session["username"] = null;
return View("login");
}
[HttpPost]
public ActionResult Login(Login objLogin)
{
var getValidUser = dbObj.Login.FirstOrDefault((p) => p.UserName == objLogin.UserName && p.Password == objLogin.Password);
if (getValidUser != null)
{
Session["username"] = objLogin.UserName;
return RedirectToAction("Index");
}
else
{
ViewBag.LoginFaild = "Invalid username or password";
return View("login");
}
}
public IList<Item> getAllItems()
{
IList<Item> items = new List<Item>();
items = dbObj.Item.ToList();
return items;
}
public int AddCart(int ItemId)
{
string username = Session["username"].ToString();
Cart objcart = new Cart()
{
UserName = username,
ItemId = ItemId
};
dbObj.Cart.Add(objcart);
dbObj.SaveChanges();
int count = dbObj.Cart.Where(s => s.UserName == username).Count();
return count;
}
public PartialViewResult GetCartItems()
{
string username = Session["username"].ToString();
var sum = 0;
var GetItemsId = dbObj.Cart.Where(s => s.UserName == username).Select(u => u.ItemId).ToList();
var GetCartItem = from itemList in dbObj.Item where GetItemsId.Contains(itemList.Id) select itemList;
foreach (var totalsum in GetCartItem)
{
sum = sum + totalsum.Price;
sum = sum - ((totalsum.Price * totalsum.Offer) / 100);
}
ViewBag.Total = sum;
return PartialView("_cartItem", GetCartItem);
}
public PartialViewResult DeleteCart(int itemId)
{
string getName = Session["username"].ToString();
Cart removeCart = dbObj.Cart.FirstOrDefault(s => s.UserName == getName && s.ItemId == itemId);
dbObj.Cart.Remove(removeCart);
dbObj.SaveChanges();
return GetCartItems();
}
}
}
Step 6- Add a strolngly typed view INDEX. which will show list of Items and Cart count. Add the following code to Index View.
@model IEnumerable<ShopingCartDemo.Models.Item>
<script src="../../Scripts/jquery-2.1.1.js" type="text/javascript"></script>
<script src="~/Scripts/bootstrap-modal.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="../../Content/Style.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
$('.divAddCart').on('click', function () {
var getItemId =parseInt($(this).closest('td').prop('id'));
var getUserName = $('.divName').html();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'Home/AddCart',
data: "{ 'itemId':' " + getItemId + "' }",
success: function (data) {
$('#spnCart').html(data)
},
error: function (data) {
alert(data);
}
});
});
$('#spnCart').on('click', function () {
var getName = $('.divName').html();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '/Home/GetCartItems',
success: function (data) {
$('#exampleModal').html(data);
$('#exampleModal').modal({
backdrop:false
});
},
error: function (data) {
alert(data);
}
});
});
$(document).delegate('.cartDel', 'click', function () {
var DeleteItem=parseInt($(this).closest('tr').prop('id'));
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '/Home/DeleteCart',
data: "{ 'itemId':' " + DeleteItem + "' }",
success: function (data) {
$('#exampleModal').html(data);
$('#spnCart').html($(data).find('#cartList tbody tr').length);
$('#exampleModal').modal({
backdrop: false
});
},
error: function (data) {
alert(data);
}
});
});
});
</script>
<div class="top">
<div class="divName">@ViewBag.userName</div>
<div class="divCart">
Total Items In Cart : <span id="spnCart">@ViewBag.cartCount</span>
</div>
<div class="divLgout">
@Html.ActionLink("Logout","Login")
</div>
<div class="container">
<table>
@foreach (var objItem in Model)
{
<tr>
<td id="@objItem.Id">
<div class="itemImage">
<div class="divImg"><img src="@objItem.ImagePath" height="150" width="150" /></div>
<div class="divIName">@objItem.Name</div>
</div>
<div class="itemDetails">
<div class="divDesc">@objItem.Description</div>
<div class="divCat">Category : @objItem.Category</div>
<div class="divPrice">Price : @objItem.Price</div>
<div class="divOff">Off : @objItem.Offer %</div>
<div class="divBuy">Buy</div>
<div class="divAddCart">Add To Cart</div>
</div>
</td>
</tr>
}
</table>
</div>
</div>
<div class="modal" id="exampleModal" tabindex="1000" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
</div>
Step 7- To Added Cart Item Popup, I have created a partial view , which will render on click of Total Number of item in cart . Create a partial view _cartItem, then add the following code to this partial view.
@model IEnumerable<ShopingCartDemo.Models.Item>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">
Your cart
</h4>
</div>
<div class="modal-body">
<table id="cartList">
<thead>
<tr>
<td><b>Image</b></td>
<td><b>Name</b></td>
<td><b>Price</b></td>
<td><b>Offer</b></td>
<td><b>Action</b></td>
</tr>
</thead><tbody>
@foreach (var objItem in Model)
{
<tr id="@objItem.Id">
<td>
<img src="@objItem.ImagePath" width="50" height="50" />
</td>
<td>
@objItem.Name
</td>
<td>
@objItem.Price
</td>
<td>
@objItem.Offer
</td>
<td>
<span class="cartDel">Remove</span>
</td>
</tr>
}
</tbody>
</table>
<span class="totalPrice">Total Amount @ViewBag.Total</span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Close
</button>
<button type="button" class="btn btn-primary">
Proceed
</button>
</div>
</div>
</div>