1

I have a view which I load with product data. When I press the 'Add to Basket' button I'd like the same page to reload again but I'm getting errors such as:

Object reference not set to an instance of an object.

View:

@model List<Ecommerce.Models.HomeModels.Product>

@foreach (Ecommerce.Models.HomeModels.Product product in Model)
{ // above error points here!!!!!!!!!!!
    using (Html.BeginForm())
    {                                               
        <input type="hidden" name="productId" value="@product.ID" />                    
        <input type="submit" value="Add to Basket"/> 
    }
}

Controller:

public ActionResult BuyProducts()
        {

            List<Models.HomeModels.Product> products = new List<Models.HomeModels.Product>();

            using (var reader = command.ExecuteReader()) 
            {
                while (reader.Read())
                {
                   //Method to load data into products
                }
            }

            TempData["products"] = products; 

            return View(products);
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult BuyProducts(string productID)
        {
            string id = productID;
            return View(TempData["products"]);
        }
litterbugkid
  • 3,534
  • 7
  • 36
  • 54

2 Answers2

1

TempData only exists for one request, so it is gone by the time you try to send it back (Which is why you get the error - TempData["products"] is null). Either way, you should use the post redirect get pattern, like this:

[HttpPost]
[AllowAnonymous]
public ActionResult BuyProducts(string productID)
{
    string id = productID;
    return RedirectToAction("BuyProducts");
}

The main reason is that if the user refreshes the page and you returned a view from post, the data will be posted a second time causing duplication.

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • This actually would be the correct way to go about it for the reason he stated. You could cache the products list somewhere so your not calling the database every time on the redirect, but that's a separate topic. – Justin Chmura Jan 16 '13 at 17:43
  • How would I go about caching it? Or could you please redirect me to some resources? – litterbugkid Jan 16 '13 at 17:50
  • @Neeta - Darin is a good resource for asp.net mvc 3, you should browse some of his answers because he puts out a lot of good content. Here is one of his answers on that topic: http://stackoverflow.com/a/8485517/1026459 – Travis J Jan 16 '13 at 17:52
1

TempData isn't persisted across requests. You can either use Session or ViewData to save "products"

Try one of those and see if that fixes your issue.

Justin Chmura
  • 430
  • 1
  • 4
  • 11