Vlado Pandžić
Vlado Pandžić

Reputation: 5058

Caching pages in MVC 4

I'm using sessions to implement Shopping cart. Adding to cart seems working great, but I have catching problem when I remove the item from cart. When I go back to prevous page using browser back button then return to cart page I see again previously deleted items. I see there is solution to disable caching to all MVC project which ofcourse I don't want. Other solution would be to save cart to database, but that wouldn't be good solution as I allow anonymous users to have shopping cart. This is part of code in Shopping cart view:

   @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>

Upvotes: 1

Views: 1966

Answers (1)

Steve Wortham
Steve Wortham

Reputation: 22260

For this reason I like to disable caching on the cart pages.

You can do that in MVC with the following class...

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);
    }
}

Then you can apply it to a method in your Controller like so...

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

Or I believe in MVC 3 and up you can use the built-in OutputCache attribute like this to disable caching...

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

Upvotes: 4

Related Questions