2013-04-25 107 views
1

我正在使用会话来实现购物车。添加到购物车似乎工作得很好,但是当我从购物车中取出物品时,我遇到了问题。当我使用浏览器返回按钮返回到预设页面时,返回到购物车页面,我再次看到以前删除的项目。我看到有解决方案禁用缓存到所有MVC项目当然我不想要的。其他解决方案是将购物车保存到数据库,但这不是一个好的解决方案,因为我允许匿名用户购买购物车。 这是在购物车查看部分代码:在MVC 4中缓存页面

@model Project.Model.ShoppingCart 

    foreach (var item in Model._linecollection) 
     { 
      var totalForProduct=((item.Product.Price/100.0)*item.Quantity); 
      total+=totalForProduct; 
     <tr> 
      <td>@item.Product.Name</td> 
      <td><input class=input-mini type="number" value="@item.Quantity" /></td> 
      <td>@(item.Product.Price/100.0) </td> 
      <td>@totalForProduct</td> 
      <td> 

       @using(Html.BeginForm("RemoveFromCart","Cart",FormMethod.Post,new {@id="form"})) 
       { 
       <input type="hidden" name="productId" value="@item.Product.Id" class="pToDelete"> 
        <button type="submit" class="deleteFromCart">Delete</button> 
       } 

      </td> 
     </tr> 

回答

4

出于这个原因,我喜欢在购物车页面禁用缓存。

你可以做,在MVC下面的类...

public class NoCacheAttribute : ActionFilterAttribute 
{ 
    public override void OnResultExecuting(ResultExecutingContext filterContext) 
    { 
     filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1)); 
     filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false); 
     filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches); 
     filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
     filterContext.HttpContext.Response.Cache.SetNoStore(); 

     base.OnResultExecuting(filterContext); 
    } 
} 

然后,你可以把它应用到了一种方法,你的控制器是这样的...

[NoCache] 
public ActionResult Cart() 
{ 
    ... 
} 

或者我相信在MVC 3中,您可以使用像这样内置的OutputCache属性来禁用缓存...

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")] 
public ActionResult Cart() 
{ 
    ... 
} 
+0

非常简单有效的解决方案! – 2013-04-25 23:41:21