2013-01-16 66 views
1

我有加載產品數據的視圖。當我按「添加到購物籃」按鈕,我想在同一頁面重新加載,但我得到的錯誤,如:用重新加載的錯誤數據加載視圖時出現的數據

Object reference not set to an instance of an object. 

查看:

@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"/> 
    } 
} 

控制器:

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

回答

1

TempData只對一個請求存在,所以當您嘗試將其發回時(這就是爲什麼您會收到錯誤 - TempData["products"]null)。無論哪種方式,你應該使用後重定向獲取模式,比如:

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

主要的原因是,如果用戶刷新頁面,你回來從後視圖,數據將公佈第二次造成複製。

+0

謝謝,這正是我所尋找的。 – Neeta

+0

由於他陳述的原因,這其實是正確的方法。您可以將產品列表緩存在某處,以便每次重定向時不要調用數據庫,但這是一個單獨的主題。 –

+0

我會如何緩存它?或者你可以請我重定向到一些資源? – Neeta

1

TempData不是跨請求持久化的。您可以使用SessionViewData來保存"products"

嘗試其中的一種,看看是否解決了您的問題。

+0

感謝您的信息,因爲它非常有用。實際上希望有更簡單的事情。 – Neeta