using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DataTable_Demo.Controllers
{
public class ProductController : Controller
{
//
// GET: /Product/
private PMSEntities context = new PMSEntities();
public ActionResult Product()
{
List<Mst_Product> _list = new List<Mst_Product>();
_list = context.Mst_Product.ToList();
return View(_list);
}
public JsonResult AddToCart(int PID)
{
var result = new jsonMessage();
try
{
Mst_Product _Mst_Product = context.Mst_Product.Where(t => t.PID == PID).FirstOrDefault();
//define the model of crt
Cart _Cart = new Cart();
_Cart.PID = PID;
_Cart.Quantity = 1;
_Cart.DateTime = System.DateTime.Now;
_Cart.TotalPrice = Convert.ToDouble(_Mst_Product.Price);
context.Carts.Add(_Cart);
result.Message = "your product has been Added in to cart..";
result.Status = true;
context.SaveChanges();
}
catch (Exception ex)
{
ErrorLogers.ErrorLog(ex);
result.Message = "We are unable to process your request at this time. Please try again later.";
result.Status = false;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
@{
ViewBag.Title = "Product";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- add thids links for the error message-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>
@*<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<div class="w3-panel w3-animate-opacity">
<div class="w3-tag w3-jumbo">S</div>
<div class="w3-tag w3-jumbo">A</div>
<div class="w3-tag w3-jumbo">L</div>
<div class="w3-tag w3-jumbo">E</div>
</div>
<div class="w3-row-padding">
@foreach (var item in Model) {
<div class="w3-third">
<div class="w3-card">
<div class="w3-container w3-red">
<h1><b>@item.Name</b></h1>
</div>
<div class="w3-container w3-xlarge">
<p>
@item.Name<br>
<i><b>@item.Description</b></i><br>
<span class="w3-xxlarge w3-text-red"><b>@item.Name</b></span>
</p>
<p>
<del>$400</del> <span class="w3-tag w3-yellow">New!</span><br>
Now only @item.Price !!!
</p>
</div>
<div class="w3-container w3-red">
<p class="w3-opacity">Contact: Bhavdip-9825891108</p>
</div>
</div>
<br />
</div>
}
</div>*@
<!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='http://fonts.googleapis.com/css?family=Work+Sans:400,600,700' rel='stylesheet' type='text/css'>
<link href="~/Content/css/reset.css" rel="stylesheet" />
<link href="~/Content/css/style.css" rel="stylesheet" />
<script src="~/Content/js/modernizr.js"></script>
<title>Document</title>
</head>
<style>
.red_border {
border: 1px solid #e46262;
}
.LoadingDiv {
top: 0;
left: 0;
position: fixed;
opacity: 0.97;
z-index: 10000000;
background: Black;
height: 100%;
width: 100%;
margin: auto;
}
.dataTables_filter {
float:right;
}
</style>
<body>
<div id="dvLoader" class="LoadingDiv" style="display: none;">
<table style="height: 100%; margin: auto;">
<tr>
<td style="vertical-align: middle;">
<center>
<img src="http://www.girlsgotit.org/images/ajax-loader.gif" alt="Loading" />
</center>
</td>
</tr>
</table>
</div>
<header>
<h1>Quick Add to Cart</h1>
</header>
<a href="@Url.Action("Cart","Cart")" class="cd-cart">
<span>0</span>
</a>
<ul class="cd-gallery">
@foreach (var item in Model) {
<li>
<div class="cd-single-item">
<a href="#0">
<ul class="cd-slider-wrapper">
<li>
<img src="~/Content/img/thumb-1.jpg" alt="Preview image"></li>
<li>
<img src="~/Content/img/thumb-2.jpg" alt="Preview image"></li>
<li class="selected">
<img src="~/Content/img/thumb-1.jpg" alt="Preview image"></li>
</ul>
</a>
<div class="cd-customization">
<div class="color selected-3" data-type="select">
<ul>
<li class="color-1">color-1</li>
<li class="color-2">color-2</li>
<li class="color-3 active">color-3</li>
</ul>
</div>
<div class="size" data-type="select">
<ul>
<li class="small active">Small</li>
<li class="medium">Medium</li>
<li class="large">Large</li>
</ul>
</div>
<button class="add-to-cart" onclick="AddToCart('@item.PID');">
<em>Add to Cart</em>
<svg x="0px" y="0px" width="32px" height="32px" viewBox="0 0 32 32">
<path stroke-dasharray="19.79 19.79" stroke-dashoffset="19.79" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" d="M9,17l3.9,3.9c0.1,0.1,0.2,0.1,0.3,0L23,11" />
</svg>
</button>
</div>
<!-- .cd-customization -->
<button class="cd-customization-trigger">Customize</button>
</div>
<!-- .cd-single-item -->
<div class="cd-item-info">
<b><a href="#0">@item.Name</a></b>
<br /><span style="font-weight:normal;font-family:Arial;font-size:15px;color:gray">@item.Description</span>
<em>$@item.Price</em>
</div>
<!-- cd-item-info -->
</li>
}
</ul>
<!-- cd-gallery -->
@*<script src="js/jquery-2.1.4.js"></script>*@
<script src="~/Content/js/main.js"></script>
<!-- Resource jQuery -->
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
});
function AddToCart(PID) {
var PID = PID
$('#dvLoader').show();
$.ajax({
url: '@Url.Action("AddToCart", "Product")',
type: 'POST',
data: JSON.stringify({ "PID": parseInt(PID) }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#dvLoader').hide();
if (result.Status == "True") {
toastr.success(result.Message);
clear();
display();
}
else {
toastr.success(result.Message);
clear();
display();
}
}
});
}
</script>
Step 4
Add the cart controller and add the cart view
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DataTable_Demo.Controllers
{
public class CartController : Controller
{
//
// GET: /Cart/
private PMSEntities context = new PMSEntities();
public class Cart_Deatails
{
public int PID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<double> Price { get; set; }
public int Quantity { get; set; }
public DateTime Date { get; set; }
public double TotalPrice { get; set; }
}
public ActionResult Cart()
{
var joinedResult = (from u in context.Mst_Product
join u2 in context.Carts on u.PID equals u2.PID
select new Cart_Deatails
{
PID=u.PID,
Name = u.Name,
Description = u.Description,
Price = u.Price,
Quantity=u2.Quantity,
Date=u2.DateTime,
TotalPrice=u2.TotalPrice
}).ToList();
return View(joinedResult);
}
public ActionResult Invoice()
{
var joinedResult = (from u in context.Mst_Product
join u2 in context.Carts on u.PID equals u2.PID
select new Cart_Deatails
{
PID = u.PID,
Name = u.Name,
Description = u.Description,
Price = u.Price,
Quantity = u2.Quantity,
Date = u2.DateTime,
TotalPrice = u2.TotalPrice
}).ToList();
return View(joinedResult);
}
public JsonResult DeleteProduct(int id)
{
var result = new jsonMessage();
try
{
var a = context.Carts.Where(x => x.PID == id).FirstOrDefault();
context.Carts.Remove(a);
context.SaveChanges();
result.Message = "your product has been removed successfully..";
result.Status = true;
}
catch (Exception ex)
{
ErrorLogers.ErrorLog(ex);
result.Message = "We are unable to process your request at this time. Please try again later.";
result.Status = false;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult UpdateCart(int id, string Qty, string FinalAmount)
{
var result = new jsonMessage();
try
{
Cart a = context.Carts.Where(x => x.PID == id).FirstOrDefault();
//define the model
a.PID = Convert.ToInt32(id);
a.Quantity = Convert.ToInt32(Qty);
a.TotalPrice = Convert.ToDouble(FinalAmount);
//for Update cart..
context.Entry(a).State = EntityState.Modified;
result.Message = "";
result.Status = true;
context.SaveChanges();
}
catch (Exception ex)
{
ErrorLogers.ErrorLog(ex);
result.Message = "We are unable to process your request at this time. Please try again later.";
result.Status = false;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
@{
ViewBag.Title = "Cart";
Layout = "~/Views/Shared/_Layout.cshtml";
var count = 0;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- add thids links for the error message-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-10 col-md-offset-1">
<table class="table table-hover">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th class="text-center">Price</th>
<th class="text-center">Total</th>
<th> </th>
</tr>
</thead>
<tbody>
@for(int i=0;i<Model.Count;i++)
{
count = Model.Count;
<tr>
<td class="col-sm-8 col-md-6">
<div class="media">
<a class="thumbnail pull-left" href="#"> <img class="media-object" src="http://icons.iconarchive.com/icons/custom-icon-design/flatastic-2/72/product-icon.png" style="width: 72px; height: 72px;"> </a>
<div class="media-body">
<h4 class="media-heading"><a href="#">@Model[i].Name</a></h4>
<h5 class="media-heading"><a href="#">@Model[i].Description</a></h5>
<span>Status: </span><span class="text-success"><strong>In Stock</strong></span>
</div>
</div></td>
<td class="col-sm-1 col-md-1" style="text-align: center">
<input type="email" class="form-control" id="exampleInputEmail1_@i" onkeypress = "return isNumberKey(event)" onkeyup="counttotal('@Model[i].Price',@i,@Model[i].PID);" value="@Model[i].Quantity">
</td>
<td class="col-sm-1 col-md-1 text-center"><strong id="pricecount_@i">@Model[i].Price</strong></td>
<td class="col-sm-1 col-md-1 text-center"><strong id="finaltotal_@i">@Model[i].TotalPrice</strong></td>
<td class="col-sm-1 col-md-1">
<button type="button" class="btn btn-danger" onclick="removeproduct('@Model[i].PID')">
<span class="glyphicon glyphicon-remove"></span> Remove
</button></td>
</tr>
}
<tr>
<td> </td>
<td> </td>
<td> </td>
<td><h5>Subtotal</h5></td>
<td class="text-right"><h5><strong id="setprice">0</strong></h5></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td><h5>Estimated shipping</h5></td>
<td class="text-right"><h5><strong id="">0</strong></h5></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td><h3>Total</h3></td>
<td class="text-right"><h3><strong id="setfinaltotal">0</strong></h3></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td>
<button type="button" class="btn btn-default">
<span class="glyphicon glyphicon-shopping-cart"></span> Continue Shopping
</button></td>
<td>
<button type="button" class="btn btn-success" onclick="generateinvoice();">
Checkout <span class="glyphicon glyphicon-play"></span>
</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/ecmascript">
$(document).ready(function () {
Calculateinvoice();
});
function generateinvoice() {
window.location.href = '@Url.Action("Invoice", "Cart")';
//TempData["finaltotal"] = $("#setfinaltotal").val();
//TempData["subtotal"] = $("#setprice").val();
}
function removeproduct(pid) {
var PID = pid;
$('#dvLoader').show();
$.ajax({
url: '@Url.Action("DeleteProduct", "Cart")',
type: 'POST',
data: JSON.stringify({ "id": PID }),
contentType: 'application/json; charset=utf-8;',
success: function (result) {
$('#dvLoader').hide();
if (result.Status == "True") {
toastr.success(result.Message);
location.reload();
}
else {
toastr.success(result.Message);
location.reload();
}
}
});
}
function Calculateinvoice() {
var Price = 0.0;
var FinalToatal = 0.0;
for (var i = 0; i < 2; i++) {
Price += Number(($("#pricecount_" + i).text()));
FinalToatal += Number(($("#finaltotal_" + i).text()));
}
$("#setprice").text(parseFloat(Price).toFixed(2));
$("#setfinaltotal").text(parseFloat(FinalToatal).toFixed(2));
}
function counttotal(price, i,pid) {
var PID = pid;
var price=parseFloat(price).toFixed(2);
var qnt = parseInt($("#exampleInputEmail1_" + i).val());
if (qnt !== qnt) {
$("#exampleInputEmail1_" + i).val(1);
qnt = 1;
}
var total = price * qnt;
$("#finaltotal_"+i).text(total);
Calculateinvoice();
updatecart(PID, qnt, total);
}
function updatecart(PID, qnt, total) {
PID = parseInt(PID);
$.ajax({
url: '@Url.Action("UpdateCart", "Cart")',
type: 'POST',
data: JSON.stringify({ "id": PID, "Qty": qnt, "FinalAmount": total }),
contentType: 'application/json; charset=utf-8;',
success: function (result) {
}
});
}
function isNumberKey(evt) {
var charcode = (evt.which) ? evt.which : evt.keycode
if (charcode > 31 && (charcode < 48 || charcode > 58)
&& evt.keyCode != 35 && evt.keyCode != 36 && evt.keyCode != 37
&& evt.keyCode != 38 && evt.keyCode != 39 && evt.keyCode != 40
&& evt.keyCode != 46) {
return false;
}
else {
return true;
}
}
</script>