Reputation: 15599
Methods from my controller class
public RedirectToRouteResult AddToCart(Cart cart, int productID, string returnUrl)
{
Product product = productsRepository.Products.FirstOrDefault(p => p.ProductID == productID);
cart.AddItem(product, 1);
return RedirectToAction("Index", new { returnUrl });
}
public ViewResult Index(Cart cart, string returnUrl)
{
ViewData["returnUrl"] = returnUrl;
ViewData["CurrentCategory"] = "Cart";
return View(cart);
}
I also implemented a ModelBinder as follows:
public class CartModelBinder : IModelBinder
{
private const string cartSessionKey = "_cart";
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.Model != null)
throw new InvalidOperationException("Cannot update instances");
Cart cart = (Cart)controllerContext.HttpContext.Session[cartSessionKey];
if (cart == null)
{
cart = new Cart();
controllerContext.HttpContext.Session["cartSessionKey"] = cart;
}
return cart;
}
#endregion
}
I am not getting the cart information into my Index view so it is displaying my shopping cart as empty. Not sure what is going wrong, but I definitely do not see cart in the Index action method.
Also, my view is
<content name="TitleContent">
SportsStore: Your Cart
</content>
<content name="MainContent">
<viewdata model="DomainModel.Entities.Cart"/>
<h2>Your Cart</h2>
<table width="90%" align="center">
<thead><tr>
<th align="center">Quantity</th>
<th align="center">Item</th>
<th align="center">Price</th>
<th align="center">SubTotal</th>
</tr></thead>
<tbody>
<for each = "var line in Model.Lines" >
<tr>
<td align="center">${line.Quantity}</td>
<td align="left">${line.Product.Name}</td>
<td align="right">${line.Product.Price.ToString("c")}</td>
<td align="right">${(line.Quantity * line.Product.Price).ToString("c")}</td>
</tr>
</for>
</tbody>
<tfoot><tr>
<td colspan="3" align="right">Total:</td>
<td align="right">
${Model.ComputeTotalValue().ToString("c")}
</td>
</tr></tfoot>
</table>
<p align="center" class="actionButtons"/>
<a href="${Html.Encode(ViewData["returnUrl"])}">Continue Shopping</a>
</p>
</content>
Upvotes: 0
Views: 201
Reputation: 9163
RedirectToAction
doesn't pass any information. it only does a regular HTTP redirect.
Why not doing:
public ViewResult AddToCart(Cart cart, int productID, string returnUrl) { Product product = productsRepository.Products .FirstOrDefault(p => p.ProductID == productID); cart.AddItem(product, 1); ViewData["returnUrl"] = returnUrl; ViewData["CurrentCategory"] = "Cart"; return View("Index", cart); }
Upvotes: 1