我的控制器类的方法
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
}
我没有将购物车信息输入我的索引视图,因此它将我的购物车显示为空。不知道出了什么问题,但我肯定没有在Index动作方法中看到购物车。
另外,我的观点是
<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>
答案 0 :(得分:1)
RedirectToAction
未传递任何信息。它只进行常规的HTTP重定向。
为什么不这样做:
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); }