I have This code in a C# MVC 4 VS2012 project. I need to be able to update the shopping cart using jSON data with JQuery/AJAX, i'm using jqGrid to display the data and pulling the shopping cart items from SQL. I'm new ASP.NET MVC 4 and am having some difficulties incorporating AJAX, jSON, and jqGrid into the mix.
I've searched Google and I'm not understanding how to do this - I see many solutions using PHP and ASPX, but i'm not sure how to translate these to my C#/MVC 4 project. I've read the documentation for Ajax and tried a few things such as @ajax.actionlink and new AjaxOptions { UpdateTargetId = myDivIneedToUpdate} but i'm not sure how to implement these into the MVC solution.
If someone could point me in the right direction I would appreciate it. All of my code is on github at the link above - or github , user=jbeans99 , repo= MVC4_OSU_SportStore....
Thanks in advance!
Also, I believe I should be returning partial views in my controller as I just want the page to refresh the data for the category the user chooses; just haven't got to that part yet.
My controller looks like this:
using System;using System.Linq;using System.Web.Mvc;using MvcApp.AjaxResponses;using MvcApp.GridModels;using MvcApp.Models;namespace MvcApp.Controllers{ public class HomeController : Controller { private SportsStoreEntities db = new SportsStoreEntities(); [HttpGet] public ActionResult Index() { return View(); } // I think I should be returning a partial view here [HttpGet] public ActionResult Chess() { return View(); } [HttpPost] public ActionResult GetAllProducts(JqGridSettings gridSettings) { int totalPages; int totalRecords; var allProducts = DatabaseDAL.GetAllProductModels(); var results = jqGridDataManager.GetGridData<ProductModel>(gridSettings, allProducts, out totalPages, out totalRecords); JqGridResult result = new JqGridResult() { Page = gridSettings.PageIndex, Records = totalRecords, Total = totalPages, Rows = results.ToList() }; return Json(result, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult GetChessProducts(JqGridSettings gridSettings) { int totalPages; int totalRecords; var allProducts = DatabaseDAL.GetChessProductModels(); var results = jqGridDataManager.GetGridData<ProductModel>(gridSettings, allProducts, out totalPages, out totalRecords); JqGridResult result = new JqGridResult() { Page = gridSettings.PageIndex, Records = totalRecords, Total = totalPages, Rows = results.ToList() }; return Json(result, JsonRequestBehavior.AllowGet); } public ActionResult PostInput_Ajax(int productId) { var response = new DefaultAjaxResponse(); try { return Json(GetSuccessInputResponse(productId)); } catch (Exception) { response.AddFeedback(DefaultAjaxResponse.AjaxResponseStatusType.Error, "Input was failed! "); return Json(response); } } private string GetSuccessInputResponse(int productId) { Product selectedProduct = DatabaseDAL.GetProductByProductID(productId); return string.Format("This product is added to cart: {0}; {1}; {2:C}", selectedProduct.Name, selectedProduct.Description, selectedProduct.Price); } }}
My index.cshtml looks like this:
@model MvcApp.Models.ProductModel@{ ViewBag.Title = "Index";}@section MainHeaderContentPlaceHolder{ <div> @Html.Partial("Header") </div>}<div id="checkoutDiv"> <fieldset style="margin:1.5em; width:30%;"> <legend style="font-weight: bold; color: blue; font-size: large"">Check out</legend> <span style="color:darkgreen">Please enter your details, and we'll ship your goods right away!</span> <fieldset> <legend style="">Ship to</legend> <table style="border: 1px; width: 60%;"> <tr> <td><span>Name:</span></td> <td><input type="text" id="textboxName" /></td> </tr> </table> </fieldset> <fieldset> <legend style="">Address</legend> <table style="border: 1px; width: 60%;"> <tr> <td><span>Line 1:</span></td> <td><input type="text" id="textboxLine1" /></td> </tr> <tr> <td><span>Line 2:</span></td> <td><input type="text" id="textboxLine2" /></td> </tr> <tr> <td><span>Line 3:</span></td> <td><input type="text" id="textboxLine3" /></td> </tr> <tr> <td><span>City:</span></td> <td><input type="text" id="textboxCity" /></td> </tr> <tr> <td><span>State:</span></td> <td><input type="text" id="textboxState" /></td> </tr> <tr> <td><span>Zip:</span></td> <td><input type="text" id="textboxZip" /></td> </tr> <tr> <td><span>Country:</span></td> <td><input type="text" id="textboxCountry" /></td> </tr> </table> </fieldset> <fieldset> <legend style="">Option</legend> <table style="border: 1px; width: 60%;"> <tr> <td><input type="checkbox" id="checkboxoption">Gift wrap these items</td> </tr> </table> </fieldset> </fieldset> <br/> <button id="buttonComplete" style="margin-left: 1.5em; margin-top: 5px">Complete order</button></div><div id="cartDiv"> <fieldset style="margin:1.5em; width:60%;"> <legend style="font-weight: bold; color: blue; font-size: large">Your Cart</legend> <table style="border: 1px; width: 100%;"> <tr> <th style="width: 20%; text-align: left;">Quantity</th> <th style="width: 20%; text-align: left;">Item</th> <th style="width: 20%; text-align: left;">Price</th> <th style="width: 20%; text-align: left;">Subtotal</th> <th style="width: 20%; text-align: left;">Remove?</th> </tr> <tr id="itemRow"> <td><span id="quantityspan"></span></td> <td><span id="itemspan"></span></td> <td><span id="pricespan"></span></td> <td><span id="subspan"></span></td> <td><button id="buttonRemove">Remove</button></td> </tr> </table> </fieldset> <table style="margin-left: 1.0em;"> <tr> <td><button id="buttonContinue">Continue Shopping</button></td> <td><button id="buttonCheckout">Check out</button></td> </tr> </table></div><div id="gridDiv"> <div class="admin-grid-wrapper"> <table id="jqGrid"></table> <div id="jqGridPager"></div> </div></div><div id="dialog" title="Web Master's Message"> <p id="pdialog" style="color: red;">This functionality is currently under construction</p></div><script type="text/javascript"> $(document).ready(function () { $('#pdialog').hide(); $('#gridDiv').show(); $('#cartDiv').hide(); $('#checkoutDiv').hide(); var thisjqGrid = $("#jqGrid"); thisjqGrid.jqGrid({ url: '/Home/GetAllProducts', datatype: 'json', mtype: 'POST', caption: 'Customers', colNames: ['ProductID', 'Name', 'Description', 'Price', 'Action'], colModel: [ { name: 'ProductID', index: 'ProductID', editable: false, key: true, hidden: true }, { name: 'Name', editable: true }, { name: 'Description', editable: false }, { name: 'Price', editable: false, sortable: false, formatter: 'currency', formatoptions: { prefix: '$', suffix: '' } }, { name: 'Action', index: 'Action', width: 200, formatter: 'showlink', formatoptions: { baseLinkUrl: '#' } } ], jsonReader: { root: "Rows", page: "Page", total: "Total", records: "Records", repeatitems: false, userdata: "UserData", id: "0" }, rowNum: 5, rowList: [5, 10, 20], pager: $('#jqGridPager'), sortname: 'Name', sortorder: 'asc', viewrecords: true, multiselect: false, autowidth: true, width: 600, height: 'auto', loadComplete: function () { var ids = thisjqGrid.getDataIDs(); for (var i = 0, idCount = ids.length; i < idCount; i++) { $("#" + ids[i] + " a", thisjqGrid[0]).click(function (e) { $('#gridDiv').hide(); $('#cartDiv').show(); $('#checkoutDiv').hide(); var hash = e.currentTarget.hash;// string like "#?id=0" if (hash.substring(0, 5) === '#?id=') { var id = hash.substring(5, hash.length); var jsonId = getjsonId(id); var jsonInput = $.toJSON(jsonId); $.ajax({ url: '/home/PostInput_Ajax', type: 'POST', dataType: 'json', data: jsonInput, contentType: 'application/json; charset=utf-8', success: function (data) { debugger; var items = data.substring(30).split(';'); $('#quantityspan').text('1'); $('#itemspan').text(items[0]); $('#pricespan').text(items[2]); $('#subspan').text(items[2]); }, error: function (data) { alert("Error!"); } }); } e.preventDefault(); }); } } }); thisjqGrid.jqGrid( 'navGrid', '#jqGridPager', { edit: false, add: false, del: false, search: false }, {}, // edit options {}, // add options {}, // delete options {}, // search options {} // view options ); $("#buttonRemove").click(function (e) { e.preventDefault(); $('#itemRow').hide(); }); $("#buttonContinue").click(function (e) { e.preventDefault(); $('#gridDiv').show(); $('#cartDiv').hide(); $('#checkoutDiv').hide(); $('#pdialog').hide(); $('#itemRow').show(); }); $("#buttonCheckout").click(function (e) { e.preventDefault(); $('#gridDiv').hide(); $('#cartDiv').hide(); $('#checkoutDiv').show(); $('#pdialog').hide(); }); $("#buttonComplete").click(function (e) { e.preventDefault(); //alert("Under Construction"); $('#pdialog').show(); $("#dialog").dialog({ height: 90, width: 340 }); }); }); function getjsonId(id) { return (id == "") ? null : { ProductID: id }; } function linkformatter( cellvalue, options, rowObject){ return "<a href='home' />"; }</script>