我正在使用会话来实现购物车。添加到购物车似乎工作得很好,但我从购物车中删除项目时遇到了问题。当我使用浏览器返回按钮返回到主页时返回购物车页面我再次看到以前删除的项目。我看到有解决方案禁用缓存到我不想要的所有MVC项目。其他解决方案是将购物车保存到数据库,但这不是一个好的解决方案,因为我允许匿名用户购买购物车。 这是购物车视图中代码的一部分:
@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>
答案 0 :(得分: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);
}
}
然后您可以将其应用到Controller中的方法,就像这样......
[NoCache]
public ActionResult Cart()
{
...
}
或者我相信MVC 3及以上版本,你可以使用这样的内置OutputCache属性来禁用缓存......
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
public ActionResult Cart()
{
...
}