Step 1

Manage product,
  1. @{
  2. ViewBag.Title = "Index";
  3. // Layout = null;
  4. }
  5. <!-- Latest compiled and minified CSS -->
  6. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  7. <!-- jQuery library -->
  8. <script src="//code.jquery.com/jquery-1.12.4.js"></script>
  9. <!-- Latest compiled JavaScript -->
  10. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  11. <!-- add thids links for the error message-->
  12. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" />
  13. <script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>
  14. <!--add this link for the datatable-->
  15. <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
  16. <link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.csss" rel="stylesheet" />
  17. <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
  18. <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
  19. <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js" integrity="sha256-4F7e4JsAJyLUdpP7Q8Sah866jCOhv72zU5E8lIRER4w=" crossorigin="anonymous"></script>
  20. <link href='http://fonts.googleapis.com/css?family=Work+Sans:400,600,700' rel='stylesheet' type='text/css'>
  21. <h2>Product Master</h2>
  22. <hr />
  23. <style>
  24. .red_border {
  25. border: 1px solid #e46262;
  26. }
  27. .LoadingDiv {
  28. top: 0;
  29. left: 0;
  30. position: fixed;
  31. opacity: 0.97;
  32. z-index: 10000000;
  33. background: Black;
  34. height: 100%;
  35. width: 100%;
  36. margin: auto;
  37. }
  38. .dataTables_filter {
  39. float:right;
  40. }
  41. </style>
  42. <div class="col-md-12">
  43. <div class="col-md-4"></div>
  44. <div class="col-md-4">
  45. <div class="col-md-12">
  46. <label>Product Name :</label>
  47. <input class="form-control required" type="text" id="txtName" required />
  48. </div>
  49. <div class="col-md-12">
  50. <label>Product Descreption :</label>
  51. <textarea class="form-control required" id="txtDesc"></textarea>
  52. </div>
  53. <div class="col-md-12">
  54. <label>Product Price :</label>
  55. <input class="form-control required" onkeypress = "return isNumberKey(event)" id="txtPrice" type="text" required />
  56. </div>
  57. <div class="col-md-12">
  58. <br />
  59. <input id="btnSave" class="btn btn-success" type="button" value="Save Product" />
  60. <input id="btnCancel" class="btn btn-danger" type="button" value="Cancel" />
  61. </div>
  62. </div>
  63. <div class="col-md-4"></div>
  64. </div>
  65. <div class="col-md-12">
  66. <table id="tblProduct" class="table table-striped table-bordered" width="100%">
  67. <thead>
  68. <tr>
  69. <th >Product_ID</th>
  70. <th>Name</th>
  71. <th>Description</th>
  72. <th>Price</th>
  73. <th>Action</th>
  74. </tr>
  75. </thead>
  76. </table>
  77. </div>
  78. <div id="dvLoader" class="LoadingDiv" style="display: none;">
  79. <table style="height: 100%; margin: auto;">
  80. <tr>
  81. <td style="vertical-align: middle;">
  82. <center>
  83. <img src="http://www.girlsgotit.org/images/ajax-loader.gif" alt="Loading" />
  84. </center>
  85. </td>
  86. </tr>
  87. </table>
  88. </div>
  89. <input type="hidden" id="hdnPID" value="0" />
  90. <script type="text/javascript">
  91. $(document).ready(function () {
  92. windowResize();
  93. $(window).resize(function () {
  94. windowResize();
  95. });
  96. $('#toast-container').find('.toast-top-center').removeClass('.toast-top-center');
  97. toastr.options = {
  98. "closeButton": true,
  99. 'autoWidth': false,
  100. "debug": false,
  101. "newestOnTop": true,
  102. "progressBar": true,
  103. "positionClass": "toast-top-center",
  104. "preventDuplicates": false,
  105. "onclick": null,
  106. "showDuration": "300",
  107. "hideDuration": "1000",
  108. "timeOut": "3000",
  109. "extendedTimeOut": "1000",
  110. "showEasing": "swing",
  111. "hideEasing": "linear",
  112. "showMethod": "fadeIn",
  113. "hideMethod": "fadeOut"
  114. }
  115. $("#btnSave").click(function () {
  116. var PID = $("#hdnPID").val();
  117. var Name = $("#txtName").val();
  118. var Desc = $("#txtDesc").val();
  119. var Price = parseFloat($("#txtPrice").val()).toFixed(2);
  120. if (CheckRequiredFields()) {
  121. $('#dvLoader').show();
  122. $.ajax({
  123. url: '@Url.Action("SaveAndUpdateProduct", "Home")',
  124. type: 'POST',
  125. data: JSON.stringify({ "PID": parseInt(PID), "Name": Name, "Description": Desc, "price": Price }),
  126. dataType: "json",
  127. contentType: "application/json; charset=utf-8",
  128. success: function (result) {
  129. $('#dvLoader').hide();
  130. if (result.Status == "True") {
  131. toastr.success(result.Message);
  132. clear();
  133. display();
  134. }
  135. else {
  136. toastr.success(result.Message);
  137. clear();
  138. display();
  139. }
  140. }
  141. });
  142. }
  143. });
  144. $("#btnCancel").click(function () {
  145. clear();
  146. });
  147. });
  148. function CheckRequiredFields() {
  149. var isValid = true;
  150. $('.required').each(function () {
  151. if ($.trim($(this).val()) == '') {
  152. isValid = false;
  153. $(this).addClass('red_border');
  154. }
  155. else {
  156. $(this).removeClass('red_border');
  157. }
  158. });
  159. return isValid;
  160. }
  161. function checkemail(valemail) {
  162. var forgetfilter = /^([\w-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
  163. if (forgetfilter.test(valemail)) {
  164. return true;
  165. }
  166. else {
  167. return false;
  168. }
  169. }
  170. function clear() {
  171. $("#txtName").val("");
  172. $("#txtDesc").val("");
  173. $("#txtPrice").val("");
  174. $('#btnSave').val("Save Product");
  175. $("#hdnPID").val(0);
  176. }
  177. function display() {
  178. $('#dvLoader').show();
  179. Table = $('#tblProduct').DataTable({
  180. "processing": true,
  181. "serverSide": false,
  182. "paging": true,
  183. "ordering": true,
  184. "info": true,
  185. "searching": true,
  186. "bFilter": false,
  187. "scrollX": "100%",
  188. "scrollY": ($(window).height() - 500),
  189. "sScrollXInner": "100%",
  190. "bScrollCollapse": true,
  191. "sAjaxSource": '@Url.Action("GetProduct","Home")',
  192. "bDestroy": true,
  193. "bLengthChange": true,
  194. "bPaginate": true,
  195. "sEmptyTable": "Loading data from server",
  196. "columns": [
  197. {
  198. "sWidth": "5%",
  199. "sClass": "TextCenter PID",
  200. "render": function (data, type, row) {
  201. return row[0];
  202. }
  203. },
  204. { "sWidth": "5%", "sClass": "TextCenter Name", "render": function (data, type, row ) { return (row[1]); } },
  205. { "sWidth": "5%", "sClass": "TextCenter Desc", "render": function (data, type, row ) { return (row[2]); } },
  206. { "sWidth": "5%", "sClass": "TextCenter Price", "render": function (data, type, row ) { return (row[3]); } },
  207. {
  208. "bSortable": false,
  209. "sClass": "TextCenter",
  210. "sWidth": "3%",
  211. "render": function (data, type, row) {
  212. return '<center><a href="javascript:void(0);" onclick=deleteData("' + row[0] + '"); return false;> <i class="glyphicon glyphicon-trash"></i></a> <a href="javascript:void(0);" onclick=EditData(this); return false;> <i class="glyphicon glyphicon-edit"></i></a></center>';
  213. }, "targets": 0,
  214. }
  215. ],
  216. });
  217. $('#dvLoader').hide();
  218. }
  219. function windowResize() {
  220. display();
  221. };
  222. function deleteData(id) {
  223. var PID = parseInt(id);
  224. bootbox.confirm({
  225. title: 'Remove Customer',
  226. message: 'Are you sure want to delete this record?',
  227. buttons: {
  228. 'cancel': {
  229. label: 'No',
  230. className: 'btn-default pull-right'
  231. },
  232. 'confirm': {
  233. label: 'Yes',
  234. className: 'btn-primary margin-right-5'
  235. }
  236. },
  237. callback: function (result) {
  238. if (result) {
  239. $('#dvLoader').show();
  240. $.ajax({
  241. url: '@Url.Action("DeleteProduct", "Home")',
  242. type: 'POST',
  243. data: JSON.stringify({ "id": id }),
  244. contentType: 'application/json; charset=utf-8;',
  245. success: function (result) {
  246. windowResize();
  247. $('#dvLoader').hide();
  248. if (result.Status == "True") {
  249. toastr.success(result.Message);
  250. clear();
  251. }
  252. else {
  253. toastr.success(result.Message);
  254. }
  255. }
  256. });
  257. }
  258. }
  259. });
  260. }
  261. function EditData(row) {
  262. debugger
  263. var PID = $(row).closest('tr').find('.PID').html();
  264. $("#hdnPID").val(parseInt(PID));
  265. var Name = $(row).closest('tr').find('.Name').html();
  266. $('#txtName').val(Name);
  267. var Desc = $(row).closest('tr').find('.Desc').html();
  268. $('#txtDesc').val(Desc);
  269. var Price = $(row).closest('tr').find('.Price').html();
  270. $('#txtPrice').val(Price);
  271. $('#btnSave').val("Update Product");
  272. }
  273. function isNumberKey(evt) {
  274. var charcode = (evt.which) ? evt.which : evt.keycode
  275. if (charcode > 31 && (charcode < 48 || charcode > 58)
  276. && evt.keyCode != 35 && evt.keyCode != 36 && evt.keyCode != 37
  277. && evt.keyCode != 38 && evt.keyCode != 39 && evt.keyCode != 40
  278. && evt.keyCode != 46) {
  279. return false;
  280. }
  281. else {
  282. return true;
  283. }
  284. }
  285. </script>
Step 2

Code of controller to manage product
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. namespace DataTable_Demo.Controllers
  8. {
  9. public class HomeController : Controller
  10. {
  11. //
  12. // GET: /Home/
  13. private PMSEntities context = new PMSEntities();
  14. public ActionResult Index()
  15. {
  16. return View();
  17. }
  18. public JsonResult SaveAndUpdateProduct(int PID,string Name, string Description, float Price)
  19. {
  20. var result = new jsonMessage();
  21. try
  22. {
  23. //define the model
  24. Mst_Product _Mst_Product = new Mst_Product();
  25. _Mst_Product.PID = PID;
  26. _Mst_Product.Name = Name;
  27. _Mst_Product.Description = Description;
  28. _Mst_Product.Price = Price;
  29. //for insert recored..
  30. if (_Mst_Product.PID == 0)
  31. {
  32. context.Mst_Product.Add(_Mst_Product);
  33. result.Message = "your product has been saved success..";
  34. result.Status = true;
  35. }
  36. else //for update recored..
  37. {
  38. context.Entry(_Mst_Product).State = EntityState.Modified;
  39. result.Message = "your product has been updated successfully..";
  40. result.Status = true;
  41. }
  42. context.SaveChanges();
  43. }
  44. catch (Exception ex)
  45. {
  46. ErrorLogers.ErrorLog(ex);
  47. result.Message = "We are unable to process your request at this time. Please try again later.";
  48. result.Status = false;
  49. }
  50. return Json(result, JsonRequestBehavior.AllowGet);
  51. }
  52. public JsonResult GetProduct()
  53. {
  54. List<Mst_Product> _list = new List<Mst_Product>();
  55. try
  56. {
  57. _list = context.Mst_Product.ToList();
  58. var result = from c in _list
  59. select new[]
  60. {
  61. Convert.ToString( c.PID ), // 0
  62. Convert.ToString( c.Name ), // 1
  63. Convert.ToString( c.Description ), // 2
  64. Convert.ToString( c.Price ), // 3
  65. };
  66. return Json(new
  67. {
  68. aaData= result
  69. }, JsonRequestBehavior.AllowGet);
  70. }
  71. catch (Exception ex)
  72. {
  73. ErrorLogers.ErrorLog(ex);
  74. return Json(new
  75. {
  76. aaData = new List<string[]> { }
  77. }, JsonRequestBehavior.AllowGet);
  78. }
  79. }
  80. public JsonResult DeleteProduct(int id)
  81. {
  82. var result = new jsonMessage();
  83. try
  84. {
  85. var product = new Mst_Product { PID = id };
  86. context.Entry(product).State = EntityState.Deleted;
  87. context.SaveChanges();
  88. result.Message = "your product has been deleted successfully..";
  89. result.Status = true;
  90. }
  91. catch (Exception ex)
  92. {
  93. ErrorLogers.ErrorLog(ex);
  94. result.Message = "We are unable to process your request at this time. Please try again later.";
  95. result.Status = false;
  96. }
  97. return Json(result, JsonRequestBehavior.AllowGet);
  98. }
  99. }
  100. }
Step 3

Add the Product controller and product view for the show product page List.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace DataTable_Demo.Controllers
  7. {
  8. public class ProductController : Controller
  9. {
  10. //
  11. // GET: /Product/
  12. private PMSEntities context = new PMSEntities();
  13. public ActionResult Product()
  14. {
  15. List<Mst_Product> _list = new List<Mst_Product>();
  16. _list = context.Mst_Product.ToList();
  17. return View(_list);
  18. }
  19. public JsonResult AddToCart(int PID)
  20. {
  21. var result = new jsonMessage();
  22. try
  23. {
  24. Mst_Product _Mst_Product = context.Mst_Product.Where(t => t.PID == PID).FirstOrDefault();
  25. //define the model of crt
  26. Cart _Cart = new Cart();
  27. _Cart.PID = PID;
  28. _Cart.Quantity = 1;
  29. _Cart.DateTime = System.DateTime.Now;
  30. _Cart.TotalPrice = Convert.ToDouble(_Mst_Product.Price);
  31. context.Carts.Add(_Cart);
  32. result.Message = "your product has been Added in to cart..";
  33. result.Status = true;
  34. context.SaveChanges();
  35. }
  36. catch (Exception ex)
  37. {
  38. ErrorLogers.ErrorLog(ex);
  39. result.Message = "We are unable to process your request at this time. Please try again later.";
  40. result.Status = false;
  41. }
  42. return Json(result, JsonRequestBehavior.AllowGet);
  43. }
  44. }
  45. }
  1. @{
  2. ViewBag.Title = "Product";
  3. Layout = "~/Views/Shared/_Layout.cshtml";
  4. }
  5. <!-- Latest compiled and minified CSS -->
  6. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  7. <!-- jQuery library -->
  8. <script src="//code.jquery.com/jquery-1.12.4.js"></script>
  9. <!-- Latest compiled JavaScript -->
  10. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  11. <!-- add thids links for the error message-->
  12. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" />
  13. <script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>
  14. @*<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  15. <div class="w3-panel w3-animate-opacity">
  16. <div class="w3-tag w3-jumbo">S</div>
  17. <div class="w3-tag w3-jumbo">A</div>
  18. <div class="w3-tag w3-jumbo">L</div>
  19. <div class="w3-tag w3-jumbo">E</div>
  20. </div>
  21. <div class="w3-row-padding">
  22. @foreach (var item in Model) {
  23. <div class="w3-third">
  24. <div class="w3-card">
  25. <div class="w3-container w3-red">
  26. <h1><b>@item.Name</b></h1>
  27. </div>
  28. <div class="w3-container w3-xlarge">
  29. <p>
  30. @item.Name<br>
  31. <i><b>@item.Description</b></i><br>
  32. <span class="w3-xxlarge w3-text-red"><b>@item.Name</b></span>
  33. </p>
  34. <p>
  35. <del>$400</del> <span class="w3-tag w3-yellow">New!</span><br>
  36. Now only @item.Price !!!
  37. </p>
  38. </div>
  39. <div class="w3-container w3-red">
  40. <p class="w3-opacity">Contact: Bhavdip-9825891108</p>
  41. </div>
  42. </div>
  43. <br />
  44. </div>
  45. }
  46. </div>*@
  47. <!doctype html>
  48. <html lang="en" class="no-js">
  49. <head>
  50. <meta charset="UTF-8">
  51. <meta name="viewport" content="width=device-width, initial-scale=1">
  52. <link href='http://fonts.googleapis.com/css?family=Work+Sans:400,600,700' rel='stylesheet' type='text/css'>
  53. <link href="~/Content/css/reset.css" rel="stylesheet" />
  54. <link href="~/Content/css/style.css" rel="stylesheet" />
  55. <script src="~/Content/js/modernizr.js"></script>
  56. <title>Document</title>
  57. </head>
  58. <style>
  59. .red_border {
  60. border: 1px solid #e46262;
  61. }
  62. .LoadingDiv {
  63. top: 0;
  64. left: 0;
  65. position: fixed;
  66. opacity: 0.97;
  67. z-index: 10000000;
  68. background: Black;
  69. height: 100%;
  70. width: 100%;
  71. margin: auto;
  72. }
  73. .dataTables_filter {
  74. float:right;
  75. }
  76. </style>
  77. <body>
  78. <div id="dvLoader" class="LoadingDiv" style="display: none;">
  79. <table style="height: 100%; margin: auto;">
  80. <tr>
  81. <td style="vertical-align: middle;">
  82. <center>
  83. <img src="http://www.girlsgotit.org/images/ajax-loader.gif" alt="Loading" />
  84. </center>
  85. </td>
  86. </tr>
  87. </table>
  88. </div>
  89. <header>
  90. <h1>Quick Add to Cart</h1>
  91. </header>
  92. <a href="@Url.Action("Cart","Cart")" class="cd-cart">
  93. <span>0</span>
  94. </a>
  95. <ul class="cd-gallery">
  96. @foreach (var item in Model) {
  97. <li>
  98. <div class="cd-single-item">
  99. <a href="#0">
  100. <ul class="cd-slider-wrapper">
  101. <li>
  102. <img src="~/Content/img/thumb-1.jpg" alt="Preview image"></li>
  103. <li>
  104. <img src="~/Content/img/thumb-2.jpg" alt="Preview image"></li>
  105. <li class="selected">
  106. <img src="~/Content/img/thumb-1.jpg" alt="Preview image"></li>
  107. </ul>
  108. </a>
  109. <div class="cd-customization">
  110. <div class="color selected-3" data-type="select">
  111. <ul>
  112. <li class="color-1">color-1</li>
  113. <li class="color-2">color-2</li>
  114. <li class="color-3 active">color-3</li>
  115. </ul>
  116. </div>
  117. <div class="size" data-type="select">
  118. <ul>
  119. <li class="small active">Small</li>
  120. <li class="medium">Medium</li>
  121. <li class="large">Large</li>
  122. </ul>
  123. </div>
  124. <button class="add-to-cart" onclick="AddToCart('@item.PID');">
  125. <em>Add to Cart</em>
  126. <svg x="0px" y="0px" width="32px" height="32px" viewBox="0 0 32 32">
  127. <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" />
  128. </svg>
  129. </button>
  130. </div>
  131. <!-- .cd-customization -->
  132. <button class="cd-customization-trigger">Customize</button>
  133. </div>
  134. <!-- .cd-single-item -->
  135. <div class="cd-item-info">
  136. <b><a href="#0">@item.Name</a></b>
  137. <br /><span style="font-weight:normal;font-family:Arial;font-size:15px;color:gray">@item.Description</span>
  138. <em>[email protected]</em>
  139. </div>
  140. <!-- cd-item-info -->
  141. </li>
  142. }
  143. </ul>
  144. <!-- cd-gallery -->
  145. @*<script src="js/jquery-2.1.4.js"></script>*@
  146. <script src="~/Content/js/main.js"></script>
  147. <!-- Resource jQuery -->
  148. </body>
  149. </html>
  150. <script type="text/javascript">
  151. $(document).ready(function () {
  152. });
  153. function AddToCart(PID) {
  154. var PID = PID
  155. $('#dvLoader').show();
  156. $.ajax({
  157. url: '@Url.Action("AddToCart", "Product")',
  158. type: 'POST',
  159. data: JSON.stringify({ "PID": parseInt(PID) }),
  160. dataType: "json",
  161. contentType: "application/json; charset=utf-8",
  162. success: function (result) {
  163. $('#dvLoader').hide();
  164. if (result.Status == "True") {
  165. toastr.success(result.Message);
  166. clear();
  167. display();
  168. }
  169. else {
  170. toastr.success(result.Message);
  171. clear();
  172. display();
  173. }
  174. }
  175. });
  176. }
  177. </script>
Step 4

Add the cart controller and add the cart view
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. namespace DataTable_Demo.Controllers
  8. {
  9. public class CartController : Controller
  10. {
  11. //
  12. // GET: /Cart/
  13. private PMSEntities context = new PMSEntities();
  14. public class Cart_Deatails
  15. {
  16. public int PID { get; set; }
  17. public string Name { get; set; }
  18. public string Description { get; set; }
  19. public Nullable<double> Price { get; set; }
  20. public int Quantity { get; set; }
  21. public DateTime Date { get; set; }
  22. public double TotalPrice { get; set; }
  23. }
  24. public ActionResult Cart()
  25. {
  26. var joinedResult = (from u in context.Mst_Product
  27. join u2 in context.Carts on u.PID equals u2.PID
  28. select new Cart_Deatails
  29. {
  30. PID=u.PID,
  31. Name = u.Name,
  32. Description = u.Description,
  33. Price = u.Price,
  34. Quantity=u2.Quantity,
  35. Date=u2.DateTime,
  36. TotalPrice=u2.TotalPrice
  37. }).ToList();
  38. return View(joinedResult);
  39. }
  40. public ActionResult Invoice()
  41. {
  42. var joinedResult = (from u in context.Mst_Product
  43. join u2 in context.Carts on u.PID equals u2.PID
  44. select new Cart_Deatails
  45. {
  46. PID = u.PID,
  47. Name = u.Name,
  48. Description = u.Description,
  49. Price = u.Price,
  50. Quantity = u2.Quantity,
  51. Date = u2.DateTime,
  52. TotalPrice = u2.TotalPrice
  53. }).ToList();
  54. return View(joinedResult);
  55. }
  56. public JsonResult DeleteProduct(int id)
  57. {
  58. var result = new jsonMessage();
  59. try
  60. {
  61. var a = context.Carts.Where(x => x.PID == id).FirstOrDefault();
  62. context.Carts.Remove(a);
  63. context.SaveChanges();
  64. result.Message = "your product has been removed successfully..";
  65. result.Status = true;
  66. }
  67. catch (Exception ex)
  68. {
  69. ErrorLogers.ErrorLog(ex);
  70. result.Message = "We are unable to process your request at this time. Please try again later.";
  71. result.Status = false;
  72. }
  73. return Json(result, JsonRequestBehavior.AllowGet);
  74. }
  75. public JsonResult UpdateCart(int id, string Qty, string FinalAmount)
  76. {
  77. var result = new jsonMessage();
  78. try
  79. {
  80. Cart a = context.Carts.Where(x => x.PID == id).FirstOrDefault();
  81. //define the model
  82. a.PID = Convert.ToInt32(id);
  83. a.Quantity = Convert.ToInt32(Qty);
  84. a.TotalPrice = Convert.ToDouble(FinalAmount);
  85. //for Update cart..
  86. context.Entry(a).State = EntityState.Modified;
  87. result.Message = "";
  88. result.Status = true;
  89. context.SaveChanges();
  90. }
  91. catch (Exception ex)
  92. {
  93. ErrorLogers.ErrorLog(ex);
  94. result.Message = "We are unable to process your request at this time. Please try again later.";
  95. result.Status = false;
  96. }
  97. return Json(result, JsonRequestBehavior.AllowGet);
  98. }
  99. }
  100. }
  1. @{
  2. ViewBag.Title = "Cart";
  3. Layout = "~/Views/Shared/_Layout.cshtml";
  4. var count = 0;
  5. }
  6. <!-- Latest compiled and minified CSS -->
  7. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  8. <!-- jQuery library -->
  9. <script src="//code.jquery.com/jquery-1.12.4.js"></script>
  10. <!-- Latest compiled JavaScript -->
  11. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  12. <!-- add thids links for the error message-->
  13. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" />
  14. <script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>
  15. <div class="container">
  16. <div class="row">
  17. <div class="col-sm-12 col-md-10 col-md-offset-1">
  18. <table class="table table-hover">
  19. <thead>
  20. <tr>
  21. <th>Product</th>
  22. <th>Quantity</th>
  23. <th class="text-center">Price</th>
  24. <th class="text-center">Total</th>
  25. <th> </th>
  26. </tr>
  27. </thead>
  28. <tbody>
  29. @for(int i=0;i<Model.Count;i++)
  30. {
  31. count = Model.Count;
  32. <tr>
  33. <td class="col-sm-8 col-md-6">
  34. <div class="media">
  35. <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>
  36. <div class="media-body">
  37. <h4 class="media-heading"><a href="#">@Model[i].Name</a></h4>
  38. <h5 class="media-heading"><a href="#">@Model[i].Description</a></h5>
  39. <span>Status: </span><span class="text-success"><strong>In Stock</strong></span>
  40. </div>
  41. </div></td>
  42. <td class="col-sm-1 col-md-1" style="text-align: center">
  43. <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">
  44. </td>
  45. <td class="col-sm-1 col-md-1 text-center"><strong id="pricecount_@i">@Model[i].Price</strong></td>
  46. <td class="col-sm-1 col-md-1 text-center"><strong id="finaltotal_@i">@Model[i].TotalPrice</strong></td>
  47. <td class="col-sm-1 col-md-1">
  48. <button type="button" class="btn btn-danger" onclick="removeproduct('@Model[i].PID')">
  49. <span class="glyphicon glyphicon-remove"></span> Remove
  50. </button></td>
  51. </tr>
  52. }
  53. <tr>
  54. <td> </td>
  55. <td> </td>
  56. <td> </td>
  57. <td><h5>Subtotal</h5></td>
  58. <td class="text-right"><h5><strong id="setprice">0</strong></h5></td>
  59. </tr>
  60. <tr>
  61. <td> </td>
  62. <td> </td>
  63. <td> </td>
  64. <td><h5>Estimated shipping</h5></td>
  65. <td class="text-right"><h5><strong id="">0</strong></h5></td>
  66. </tr>
  67. <tr>
  68. <td> </td>
  69. <td> </td>
  70. <td> </td>
  71. <td><h3>Total</h3></td>
  72. <td class="text-right"><h3><strong id="setfinaltotal">0</strong></h3></td>
  73. </tr>
  74. <tr>
  75. <td> </td>
  76. <td> </td>
  77. <td> </td>
  78. <td>
  79. <button type="button" class="btn btn-default">
  80. <span class="glyphicon glyphicon-shopping-cart"></span> Continue Shopping
  81. </button></td>
  82. <td>
  83. <button type="button" class="btn btn-success" onclick="generateinvoice();">
  84. Checkout <span class="glyphicon glyphicon-play"></span>
  85. </button></td>
  86. </tr>
  87. </tbody>
  88. </table>
  89. </div>
  90. </div>
  91. </div>
  92. <script type="text/ecmascript">
  93. $(document).ready(function () {
  94. Calculateinvoice();
  95. });
  96. function generateinvoice() {
  97. window.location.href = '@Url.Action("Invoice", "Cart")';
  98. //TempData["finaltotal"] = $("#setfinaltotal").val();
  99. //TempData["subtotal"] = $("#setprice").val();
  100. }
  101. function removeproduct(pid) {
  102. var PID = pid;
  103. $('#dvLoader').show();
  104. $.ajax({
  105. url: '@Url.Action("DeleteProduct", "Cart")',
  106. type: 'POST',
  107. data: JSON.stringify({ "id": PID }),
  108. contentType: 'application/json; charset=utf-8;',
  109. success: function (result) {
  110. $('#dvLoader').hide();
  111. if (result.Status == "True") {
  112. toastr.success(result.Message);
  113. location.reload();
  114. }
  115. else {
  116. toastr.success(result.Message);
  117. location.reload();
  118. }
  119. }
  120. });
  121. }
  122. function Calculateinvoice() {
  123. var Price = 0.0;
  124. var FinalToatal = 0.0;
  125. for (var i = 0; i < 2; i++) {
  126. Price += Number(($("#pricecount_" + i).text()));
  127. FinalToatal += Number(($("#finaltotal_" + i).text()));
  128. }
  129. $("#setprice").text(parseFloat(Price).toFixed(2));
  130. $("#setfinaltotal").text(parseFloat(FinalToatal).toFixed(2));
  131. }
  132. function counttotal(price, i,pid) {
  133. var PID = pid;
  134. var price=parseFloat(price).toFixed(2);
  135. var qnt = parseInt($("#exampleInputEmail1_" + i).val());
  136. if (qnt !== qnt) {
  137. $("#exampleInputEmail1_" + i).val(1);
  138. qnt = 1;
  139. }
  140. var total = price * qnt;
  141. $("#finaltotal_"+i).text(total);
  142. Calculateinvoice();
  143. updatecart(PID, qnt, total);
  144. }
  145. function updatecart(PID, qnt, total) {
  146. PID = parseInt(PID);
  147. $.ajax({
  148. url: '@Url.Action("UpdateCart", "Cart")',
  149. type: 'POST',
  150. data: JSON.stringify({ "id": PID, "Qty": qnt, "FinalAmount": total }),
  151. contentType: 'application/json; charset=utf-8;',
  152. success: function (result) {
  153. }
  154. });
  155. }
  156. function isNumberKey(evt) {
  157. var charcode = (evt.which) ? evt.which : evt.keycode
  158. if (charcode > 31 && (charcode < 48 || charcode > 58)
  159. && evt.keyCode != 35 && evt.keyCode != 36 && evt.keyCode != 37
  160. && evt.keyCode != 38 && evt.keyCode != 39 && evt.keyCode != 40
  161. && evt.keyCode != 46) {
  162. return false;
  163. }
  164. else {
  165. return true;
  166. }
  167. }
  168. </script>