2015-11-01 53 views
-1

我們創建了一個示例自定義類「Customer」。Peek不在MVC中工作4

public class Customer 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string Addresss { get; set; } 
} 

我們存儲在TempData中。

public ActionResult Index() 
{ 
    Customer customer = new Customer() 
    { 
    FirstName = "FirstName", 
    LastName = "LastName", 
    Addresss = "Address" 
    }; 

    TempData["Customer"] = customer; 
    return RedirectToAction("About"); 
} 

重定向到另一個操作方法並呈現「關於」視圖。

public ActionResult About() 
{ 
    Customer customer = new Customer(); 
    if (TempData["Customer"] != null) 
    { 
    customer = TempData.Peek("Customer") as Customer; 
    }  
    return View(); 
    } 

在視圖中,一個鏈接按鈕是有「聯繫」。當我們點擊這個按鈕將進入操作方法「聯繫」。

public ActionResult Contact() 
{ 
Customer customer = new Customer(); 
if (TempData["Customer"] != null) 
{ 
    customer = TempData["Customer"] as Customer; 
} 
return View(); 
} 

但在這種情況下TempData [「Customer」]爲空。爲什麼TempData [「Customer」]在使用peek時不會保留數據?

+0

很好,它的名字叫做'TempData'是有原因的,我猜。如果你想保存它,你可以將它保存在'application data'或'session data'中(如果這對你有用的話)。 但我不明白的是你的設計是什麼?爲什麼關於頁面數據在索引內初始化?以及爲什麼當你使用'redirectToAction'方法傳遞參數時使用'TempData'傳遞參數。 – LiranBo

+0

我是MVC中的新手。其實我想檢查TempData,當我們使用「Peek」時,可以堅持兩個請求。同樣的情況是在「保持」中工作。但它不適用於「Peek」。 –

回答

3

您正在嘗試執行雙TeamData讀取。

我想這將是不偷看預讀/檢查值正確的方法。

public ActionResult Contact() 
{ 
    Customer customer = TempData.Peek("Customer") as Customer; 
    if (customer == null) 
    { 
     customer = new Customer(); 
    } 
    return View(); 
} 
1

您正在讀取if語句條件中的「客戶」值。所以這個值一旦被讀取就會被銷燬。因此,它將在第二次讀取TempData.Peek(「Customer」)時返回null。

Customer customer = (Customer)TempData["Customer"]; 
if (customer != null) 
{ 
    //Do your work. 
} 
0

TempData保存HTTP請求的時間信息。這意味着只能從一個網頁到另一個 因爲當你點擊聯繫人操作鏈接要重定向第二次和TempData的字典的壽命結束 編號:TempData