Ajax.BeginForm refresh partial..? - c#

Okay so, I have a form that is posting using ajax...
<% using(Ajax.BeginForm(new AjaxOptions() { OnBegin="onBegin", OnSuccess = "onSuccess", OnFailure="onFailure" })) { %>
On the server side I am passing back from the controller a Json object. Now, when the OnSuccess event fires I can get to the Json object by using "result.get_response().get_object()"...
My question is, I need to be able to refresh a partial on the page with a list of items that are in the Json object...
Thoughts on how I can do this..?

Use jQuery, and spin through the returned JSON object, building whatever you like.
Example:
$.each(json, function(i, item) {
//Add a dinner to the list on the right
$('#dinnerList').append($('<li/>')
.attr("class", "dinnerItem")
.append($('<a/>').attr("href", "/Dinners/Details/" + item.ID)
.html(item.Name)).append("SomeThing"));
});

I think that you will find the below code helpful.
Firstly, create an AJAX form with
RefreshAjaxList: the name ajax action of current controller
string.empty (optional)
AJAX option
id of form (optional)
when click status, we will edit the status call server to update the status
after edit the status, we call submit button to call RefreshAjaxList; the button is display:none
in this example, I have one controller: AjaxController with 2 actions:
public ActionResult UpdateStatus(int contactId, Status contactStatus)
{
ContactRepository repo = new ContactRepository();
repo.UpdateStatus(contactId, contactStatus);
return Json("success:true");
}
[AcceptVerbs(HttpVerbs.Post)]
[ActionName("RefreshAjaxList")]
public ActionResult RefreshContact()
{
ContactRepository repo = new ContactRepository();
IList<Contact> list = repo.List();
return PartialView("AjaxUc/AjaxList", repo.List());
}
JavaScript:
var status = { active: 1, inactive: 0 };
function editStatus(cell, id, active) {
if (active)
cell.innerHTML = "<input type='radio' checked='true' name='active" + id + "' onclick='updateStatus(this, " + id + ", true);'>Active</input>" +
"<input type='radio' name='active" + id + "' onclick='updateStatus(this, " + id + ", false);'>Inactive</input>";
else
cell.innerHTML = "<input type='radio' name='active" + id + "' onclick='updateStatus(this, " + id + ", true);'>Active</input>" +
"<input type='radio' checked='false' name='active" + id + "' onclick='updateStatus(this, " + id + ", false);'>Inactive</input>";
}
function updateStatus(radio, id, active) {
if (radio.checked != active) {
if (confirm("Do you want to change the status of the contract?")) {
if (active)
cStatus = status.active;
else
cStatus = status.inactive;
$.ajax({
url: 'Ajax/UpdateStatus',
dataType: "json",
data: { contactId: id, contactStatus: cStatus },
success: function(html) {
jQuery("#divAjaxList").submit();
},
error: function(request, desc, ex) {
alert(desc);
}
});
}
}
}
Your ASP script:
<% using (Ajax.BeginForm("RefreshAjaxList", "abc", new AjaxOptions() { UpdateTargetId = "divContent" }, new { #id = "divAjaxList" }))
{%>
<div id="divContent">
<table>
<tr>
<th>
</th>
<th>
Id
</th>
<th>
FirstName
</th>
<th>
LastName
</th>
<th>
Phone
</th>
<th>
Email
</th>
<th>
Status
</th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%= Html.ActionLink("Edit", "Edit", new { id = item.Id })%>
|
<%= Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ })%>
</td>
<td>
<%= Html.Encode(item.Id)%>
</td>
<td>
<%= Html.Encode(item.FirstName)%>
</td>
<td>
<%= Html.Encode(item.LastName)%>
</td>
<td>
<%= Html.Encode(item.Phone)%>
</td>
<td>
<%= Html.Encode(item.Email)%>
</td>
<td ondblclick="editStatus(this,<%=item.Id %>, <%= item.Status.GetHashCode() %>);">
<%= item.Status== Status.Active ? "Active" :"Inactive" %>
</td>
</tr>
<% } %>
</table>
<input type="submit" id="refresh" style="display:none" />
</div>
<% } %>
For more info, mail to pnguyen2#firstlook.com for further discussion.
Hope this can help u.

create the user control for the list of items to be displayed and render it as partial by passing the json data to the UC. This will refresh partially

You can also use JTemplate to render JSON data

Related

How to insert and fetch Data from Sessions instead of Database in Asp.net MVC C#

Right now I have understanding of applying CRUD operations with or without page refresh. But now what I want is to save and retrieve data from sessions instead of database. I have been searching to this matter from previous two days but I haven't found any credible resource to follow which can resolve or give explanation in detail how this can be done ?.
I know that in the scenario of online shopping or online quiz systems ,It is highly preferably to use sessions to store temporary data instead of saving it to database which becomes costly due to high consumption of resources.
I am Beginner to this technology if someone resolve or share some credible links of tutorials to follow it would be really appreciable, Thanks in advance.
You can declare a global session variable and a global GUID datatype variable(for generation of unique Id as a primary Key) in your controller like this.
public List<Models.Details> SessionList
{
get
{
var obj = Session["myList"];
if (obj == null) { obj = Session["myList"] = new List<Models.Details>(); }
return (List<Models.Details>)obj;
}
set
{
Session["myList"] = value;
}
}
public Guid guid;
then You can use them in your post method for insertion of data into session like this
public ActionResult Test(Models.Details[] itemlist)
{
foreach (Models.Details d in itemlist)
{
guid = Guid.NewGuid();
d.IdString = guid;
SessionList.Add(d);
}
return Json(new { success = true, id = itemlist[0].IdString, name = itemlist[0].Name, city = itemlist[0].City, country = itemlist[0].Country });
}
return json is used here to give back a response to ajax call, It depends on person if you want to append data at the end of the table you can use this line of code. If you want to append on page refresh simply add return Json("Ok").
Here is my Javascript File which is used to read and post data to controller method with an ajax call which helps us to avoid a page refresh.
$(document).ready(function(){
$("#buttonid").on("click", Submit);
function Submit() {
var itemlist = [];
//get cell values, instead of the header text.#tablePost > tbody > t
$("#tblData > tbody > tr").each(function () {
debugger;
var name = $(this).find("[name='Name[]']").val();
var city = $(this).find("[name='City[]']").val();
var country = $(this).find("[name='Country[]']").val();
var tdlist = $(this).find("td");
var Details = { Name: name, City: city, Country: country };
itemlist.push(Details);
})
console.log(itemlist)
$.ajax({
url: '/Student/Test',
dataType: "json",
data: JSON.stringify({ itemlist: itemlist }),
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response.success) {
$("#tblDetails").append(
"<tr data-record-id=" + response.id + ">" +
"<td>" + response.name + "</td>" +
"<td>" + response.city + "</td>" +
"<td>" + response.country + "</td>" +
"<td> <a class='edit-record' data-model-id=" + response.id + " onclick='EditGet(this)'><img src='/UserImages/edit.png'/></a><a class='delete' data-model-id=" + response.id + " onclick='DeleteGet(this)'><img src='/UserImages/delete.png'/></a></td>" +
"</tr>"
);
}
},
error: function () {
alert("error");
}
});
};
});
This will hopefully insert your data in session.
To view inserted data in form of tabled list you can use your get method like this as it is done below:
public ActionResult Test()
{
List<Models.Details> detaillist = new List<Models.Details>();
var data = SessionList;
var query = data.Select(x => new Models.Details
{
IdString = x.IdString,
Name = x.Name,
City = x.City,
Country = x.Country
});
detaillist = query.ToList();
return View(detaillist);
}
Here it is razor view for insertion of data into View Table :
#model List<Inventory.Models.Details>
<button id="btnSubmit">Submit Data</button>
#using (Html.BeginForm("Test", "Student", FormMethod.Post))
{
<table id="tblData" class=" table-responsive table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Country</th>
<th>Options</th>
</tr>
</thead>
<tbody></tbody>
</table>
<input type="button" value="submit" id="btnInsert" />
<table id="tblDetails" class=" table-responsive table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Country</th>
<th>Options</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr data-record-id="#item.Id">
<td>#item.Name</td>
<td>#item.City</td>
<td>#item.Country</td>
<td>
<a class="edit-record" data-model-id="#item.Id" onclick="EditGet(this)" href="javascript:;">
<img id="image" src="/UserImages/edit.png" />
</a>
<a class="deleteimage" onclick="DeleteGet(this)" data-model-id="#item.Id">
<img src="/UserImages/delete.png" />
</a>
</td>
</tr>
}
</tbody>
</table>}
As you have mentioned above that you have done all CRUD operations, This answer is just an Idea of how data is inserted and fetched from a session. By following the same strategy as this one will help you out to complete all of the remaining operation you have in CRUD. I hope this post will help you out.

Selection in the Controller is not matching

I got this error when I am trying to remove the item from the Cart table.
HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Panier/RemoveFromCart/1. This URL seems to be fine with me. It should branch to the PanierController at RemoveCart. I don't understand why it is not branching.
Thanks
Index.cshtml
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.4.4.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Document.ready -> link up remove event handler
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart", {"id": recordToDelete },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
});
}
});
});
</script>
<h3>
<em>Details</em> du panier:
</h3>
<p class="button">
#Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description,"Details", "Store", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td id="item-count-#item.ProduitId">
#item.Quantite
</td>
<td>
#Html.ActionLink("Enlever du panier", "RemoveFromCart", "Panier", new { id =
item.ProduitId }, null)
</td>
</tr>
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
PanierController.cs
namespace Tp1WebStore3.Controllers
{
public class PanierController : Controller
{
Tp1WebStoreDBEntities dbProduit = new Tp1WebStoreDBEntities();
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the product to display confirmation
string produitDescription = dbProduit.Paniers
.Single(item => item.PanierId == id).Produit.Description;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(produitDescription) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return View("Details");
}
Your RemoveFromCart controller action is decorated with the [HttpPost] attribute meaning that it is ONLY accessible by POST verbs. But in your view you seem to have generated some action link to it:
#Html.ActionLink(
"Enlever du panier",
"RemoveFromCart",
"Panier",
new { id = item.ProduitId },
null
)
But as you are well aware, an Html.ActionLink translates into an <a> tag in your markup which obviously is sending a GET request to the server when clicked.
So basically you have 3 possibilities here:
Use an Html.BeginForm instead of an ActionLink to refer to this action which would allow you to send a POST request
Get rid of the [HttpPost] attribute from your RemoveFromCart action
AJAXify the anchor which would allow you to use a POST request.

ASP.NET MVC 3 NOT showing appropriate view, action called using jquery

I have a small problem.
My action is :
public ViewResult SearchForRooms(int HotelDDL)
{
List<Room> roomsInHotel = bl.ReturnRoomsPerHotel(HotelDDL);
return View(roomsInHotel);
}
Here is the jquery that is calling the action:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#HotelDDL").change(function () {
var text = $("#HotelDDL option:selected").text();
var value = $("#HotelDDL option:selected").val();
alert("Selected text=" + text + " Selected value= " + value);
$.post("/Home/SearchForRooms",
{
HotelDDL: $("#HotelDDL option:selected").val()
});
});
});
</script>
And finally, here is the View that should be called:
#model IEnumerable<RoomReservation.Entities.Entities.Room>
#{
ViewBag.Title = "Search";
}
<h2>Result</h2>
<table>
<tr>
<th>
City
</th>
<th>
Hotel
</th>
<th>
Room label
</th>
<th>
Number of beds
</th>
<th>
Price per night
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelitem=>item.Hotel.City.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Hotel.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.NumberOfBeds)
</td>
<td>
#Html.DisplayFor(modelItem => item.PricePerNight)
</td>
</tr>
}
</table>
Everthing is working ok (databse return all rooms correctly) except final view rendering.
I have tried Phil's tool but it doesn't give me any suspicious hints:
RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
So, why is it not showing after jscript send it's post method to SearchForRooms()?
Thank you
P.S. If you need any other piece of code please just say so.
Note that doing an ajax post will not refresh or redirect the page like a classic post would.
The view is not showing because there is no where to place it. You post successfully, and return a view successfully but then do nothing with it. If you want to show the returned view, then you have to append it to the dom somehow. Here is a common method:
<div id="successDiv"></div>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#HotelDDL").change(function () {
var text = $("#HotelDDL option:selected").text();
var value = $("#HotelDDL option:selected").val();
alert("Selected text=" + text + " Selected value= " + value);
$.post("/Home/SearchForRooms",
{
HotelDDL: $("#HotelDDL option:selected").val()
}, function(result){//add callback for success - result is the returned view
$("#successDiv").html(result);//place the view inside of the div
});
});
});
</script>
Comment Response
#TunAntun - You should use a classic post if you want the view to have its own page. There is no way to accomplish this from ajax. You could do this with javascript though
$.post("/Home/SearchForRooms",
{
HotelDDL: $("#HotelDDL option:selected").val()
}, function(result){//add callback for success - result is the returned view
$("#successDiv").html(result);//place the view inside of the div
});
would become
var postForm = document.createElement("form");
postForm.setAttribute("method","post");
postForm.setAttribute("action","/Home/SearchForRooms");
var postVal = document.createElement("input");
postVal.setAttribute("type","hidden");
postVal.setAttribute("name","HotelDDL");
postVal.setAttribute("value",$("#HotelDDL option:selected").val() );
postForm.appendChild(postVal);
document.body.appendChild(postForm);
$(postForm).submit();
This will dynamically issue the post you wanted. Then in your controller it will properly redirect or return a view. It is highly suggested that when returning a view from a [HttpPost] that you use RedirectToAction and then return the view from a [HttpGet] method in order to prevent refresh from reposting old data.

How can I update a Table without refresh the entire site razor

Hi I'm working on a table
I cannot atm update the table without the site refreshing.
I need a way to easily
Add a row ,Delete a row, Modify a row in a table's content.
my table is build like this.
{....}
#using (Html.BeginForm())
{
<fieldset>
<legend>ShiftTypes</legend>
<table class="EditableTable" id="EditableTableShiftTypes">
<thead>
<tr>
<th>
#:
</th>
<th>
ShiftName:
</th>
<th>
ShiftCode:
</th>
<th>
Suplement:
</th>
<th>
ExtraSuplement:
</th>
<th>
</th>
</tr>
</thead>
<tbody>
#foreach (BPOPortal.Domain.Models.ShiftTypeView type in Model.ShiftTypeList)
{
<tr>
<td>
#type.ID
</td>
<td>
#type.ShiftName
</td>
<td>
#type.Name
</td>
<td>
#type.Supplement
</td>
<td>
#type.OneTimePayment
</td>
<td>
<button>
Delete</button>
</td>
</tr>
}
<tr>
<td>
<label>
</label>
</td>
<td>
#Html.Editor("ShiftName")
</td>
<td>
#Html.Editor("ShiftCode")
</td>
<td>
#Html.Editor("Suplement")
</td>
<td>
#Html.DropDownList("ExtraSuplement", new SelectListItem[] { new SelectListItem() { Text = "yes", Value = "true", Selected = false }, new SelectListItem() { Text = "No", Value = "false", Selected = false } }, "--Choose--")
</td>
<td>
<button id="AddButton">
Add</button>
</td>
</tr>
</tbody>
</table>
<button type="submit" id="Gem">
Save</button>
</fieldset>
{....}
I've Tried to use Ajax in the following way but it refreshes the entire page.
{....}
var ID= 2;
$("#AddButton").click(function(){
var ShiftName= $('#ShiftName').attr('value');
var ShiftCode= $('#ShiftCode').attr('value');
var Suplement= $('#Suplement').attr('value');
var ExtraSuplement= $('#ExtraSuplement').attr('value');
$.ajax({
url: '#Url.Action("AddData", "ShiftTypesConfiguration")',
data: { ID: ID.toString(), ShiftName: $('#ShiftName').attr('value'), ShiftCode: $('#ShiftCode').attr('value'), Suplement: $('#Suplement').attr('value'), ExtraSuplement: $('#ExtraSuplement').attr('value') },
type: 'POST',
// contentType: 'application/json; charset=utf-8;',
dataType: 'json',
success: function (response)
{
function fnClickAddRow() {
$('#EditableTableShiftTypes').dataTable().fnAddData([
response.ID,
response.ShiftName,
response.ShiftCode,
response.Suplement,
response.ExtraSuplement,
"<button>Delete</button>"]); }
}
});
ID++;
});
{....}
</script>
My Method in the Controller that should handle the request.
public JsonResult AddData(string ID, string ShiftName, string ShiftCode, string Suplement, string ExtraSuplement)
{
TableViewModel tableViewModel = new TableViewModel();
tableViewModel.ID = ID;
tableViewModel.ShiftName= ShiftName;
tableViewModel.ShiftCode= ShiftCode;
tableViewModel.Suplement= Suplement;
tableViewModel.ExtraSuplement= ExtraSuplement;
return Json(tableViewModel);
}
However it doesn't seem to work Now I'm asking For Ideas and ways to make this better/easier/Working
Edit:saw a copy past Error
EDIT2: I've now changed it slightly I found that I had a error in how my script was running this is the latest. there are still problems but at least now I can see and describe the error.
this is what I changed the script is now
$("#AddButton").click(function (event) {
event.preventDefault();
var ShiftName = $('#ShiftName').attr('value');
var ShiftCode = $('#ShiftCode').attr('value');
var Suplement = $('#Suplement').attr('value');
var ExtraSuplement = $('#ExtraSuplement').attr('value');
$.ajax({
url: '#Url.Action("AddData", "ShiftTypesConfiguration")',
data: { ID: ID.toString(), ShiftName: ShiftName, ShiftCode: ShiftCode, Suplement: Suplement, ExtraSuplement: ExtraSuplement },
type: 'POST',
// contentType: 'application/json; charset=utf-8;',
dataType: 'json',
success: function (response) {
function fnClickAddRow() {
$('#EditableTableShiftTypes').dataTable().fnAddData([
response.ID,
response.ShiftName,
response.ShiftCode,
response.Suplement,
response.ExtraSuplement,
"<button>Delete</button>"]);
}
}
});
ID++;
});
now with the help of firebug I've seen that the values are back on the page but before I can see them the page is refreshed.
I am not writing in code here, but here is how you should do it.
On Add/Edit/Delete make an ajax call to your action. In your Action implement your operation (Add/Edit/Delete) and depending on operation completed successfully or failed due to some error, return a true/false flag as json.
Then in the success function success: function (response){} of the ajax call, check wether the value returned is a true/false which means success or error.
And then using some jquery you can add a row or delete a row from the table.
Check out these links : http://viralpatel.net/blogs/dynamically-add-remove-rows-in-html-table-using-javascript/

Trying to understand HttpPost in MVC3 [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
MVC(3) handleUpdate
I'm (slowly) learning how to use MVC 3 and at the moment I'm having a looking at the MvcMusicStore tutorial app on the asp.net website.
Right now I'm trying to understand how HttpPost works. From what I can gather, the user performs whatever actions they want in their browser and then with the use of jQuery, the data is posted back to the server (to the corresponding function with [HttpPost] attribute) and then in this case, a json result is sent back to the browser which handles this and updates elements accordingly.
I understand this fine, but in the particular snippet of code I'm looking at, I can't understand how the 'handleUpdate()' function is being hit when there appear to be no calls made from either the js or the server-side code. Is there something I'm missing here? Anyway here is the front-end:
#model MvcMusicStore.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Document.ready -> link up remove event handler
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart", { "id": recordToDelete },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
});
}
});
});
function handleUpdate() {
// Load and deserialize the returned JSON data
var json = context.get_data();
var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
</script>
<h3>
<em>Review</em> your cart:
</h3>
<p class="button">
#Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<table>
<tr>
<th>
Album Name
</th>
<th>
Price (each)
</th>
<th>
Quantity
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.RecordId">
<td>
#Html.ActionLink(item.Album.Title, "Details", "Store", new { id = item.AlbumId }, null)
</td>
<td>
#item.Album.Price
</td>
<td id="item-count-#item.RecordId">
#item.Count
</td>
<td>
Remove from cart
</td>
</tr>
}
<tr>
<td>
Total
</td>
<td>
</td>
<td>
</td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
and here is the (relevant) server-side code:
//
// AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
string albumName = storeDB.Carts
.Single(item => item.RecordId == id).Album.Title;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(albumName) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
}
I can see that the handleUpdate() manipulates the DOM based on the returned JSON, but I can't figure out for the life of me how it's being called? Is there some jQuery magic going on or have I completely misunderstood how this all works?
Thanks!
It's not being called.
The relevant code on the client side that calls the RemoveFromCart method on the server side is this:
if (recordToDelete != '') {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart", { "id": recordToDelete },
function (data) {
// Handle result.
});
}
Note the URL is /ShoppingCart/RemoveFromCart, which maps to the URL route for the RemoveFromCart method.
The jQuery post method is being used to make the call to the method on the controller, and then a closure (indicated by the function() { ... }) is passed, not the handleUpdate method.

Categories

Resources