0
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);
}
我還實施了ModelBinder的如下:
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
}
我沒有得到車信息到我的索引視圖,以便它顯示我的購物車爲空。不知道發生了什麼問題,但我絕對沒有在索引操作方法中看到購物車。
而且,我的觀點是
<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>
你是對的!這可能是ModelBinding沒有發生。我沒有將購物車信息放入我的索引操作方法中。 – 2010-02-01 02:53:04
有關索引操作方法的購物車信息爲空。 – 2010-02-01 03:01:38