我們創建了一個示例自定義類「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時不會保留數據?
很好,它的名字叫做'TempData'是有原因的,我猜。如果你想保存它,你可以將它保存在'application data'或'session data'中(如果這對你有用的話)。 但我不明白的是你的設計是什麼?爲什麼關於頁面數據在索引內初始化?以及爲什麼當你使用'redirectToAction'方法傳遞參數時使用'TempData'傳遞參數。 – LiranBo
我是MVC中的新手。其實我想檢查TempData,當我們使用「Peek」時,可以堅持兩個請求。同樣的情況是在「保持」中工作。但它不適用於「Peek」。 –