I am rendering out a partial view like so:
<div id="cart">
<%Html.RenderPartial("Cart", 开发者_JAVA百科Model); %>
</div>
For each line in the cart I am using a form to remove items (it is important that this works when javascript is disabled hence no Ajax.ActionLink):
<%using (Ajax.BeginForm("RemoveFromCart", "Cart", new AjaxOptions { UpdateTargetId="cart"}))
{%>
<%=Html.Hidden("ProductId", line.Product.Id)%>
<%=Html.Hidden("returnUrl", ViewData["returnUrl"])%>
<input type="image" src="<%=AppHelper.ImageUrl("delete.gif")%>" value="Remove item" />
<%} %>
And my controller action:
[HttpPost]
public ActionResult RemoveFromCart(Cart cart, int productId, string returnUrl)
{
Product p = _catalogService.GetProduct(productId);
cart.RemoveLine(p); // TODO - what about if null?
if (Request.IsAjaxRequest())
return PartialView("Cart", cart);
else
return RedirectToAction("Index", new { returnUrl });
}
From my understanding, with javascript enabled, clicking the remove button will make an async post to the action and replace the contents of the "cart" container with the updated partial view. If js is disabled, a full postback is made and the user is redirected to the index page once more.
If I add a few items to the cart and delete an item it works fine. However, if I then attempt to delete another item nothing happens. The reason for this is that looking at the page source following the successful delete, the hidden field containing the product id to remove is showing the id of the item already deleted.
Before successful delete:
<input id="ProductId" name="ProductId" type="hidden" value="6" />
<input id="ProductId" name="ProductId" type="hidden" value="22" />
<input id="ProductId" name="ProductId" type="hidden" value="47" />
After removing the third product (47) the remaining items display a hidden field of value 47. My model has certainly updated as I can see that the item is removed when stepping through the controller action but it as if my partial view is not binding properly.
Any help would be appreciated.
Thanks Ben
Put your product id in the route values for the form extension instead of a hidden field. I think that will avoid the problem entirely.
<%using (Ajax.BeginForm("RemoveFromCart", "Cart", new { id = line.Product.Id }, new AjaxOptions { UpdateTargetId="cart"}))
{%>
<%=Html.Hidden("returnUrl", ViewData["returnUrl"])%>
<input type="image" src="<%=AppHelper.ImageUrl("delete.gif")%>" value="Remove item" />
<%} %>
精彩评论