2017-07-14 126 views
2

我一直與TempData最近又面臨着混亂的情況下:TempData的持久性

假設的TempData在以下操作創建:

public ActionResult MyAction1() 
{ 
    //... 
    myTempData = TempData["myTempData"]; 
    //.. 
} 

,並預計將使用以下操作:

public ActionResult MyAction2() 
{ 
    //... 
    TempData["myTempData"] = myTempData; 
    //.. 
} 

我明白,如果我呼籲下一個請求MyAction2,在TempData值將被刪除。但是如果我打電話給其他的行動,而不是MyAction2,在下次請求時,會刪除TempData?如果確實存在,是否有任何技巧確保它存在直到會議結束?

謝謝大家。

+0

您是否試過找出?這是我的理解,這使用會話來存儲數據,並在數據被讀取時被擦除,除非它被讀取.Peek – Slicksim

+0

它將在隨後的請求(重定向)中可用,無論您使用哪種「操作方法」即將致電。 – mmushtaq

+0

@Slicksim我也這麼認爲,但也不太確定:D –

回答

2

在這裏,你去保持和皮克溫度數據對於下一個請求:

如果你不會讀溫度數據,然後將可用於下一個後續請求

So let’s discuss these four conditions in more detail 

「Tempdata helps to preserve values for a single request」. 

The other half-truth which developers do not know is or I will say which confuses developer is: 

「TempData CAN ALSO preserve values for the next request depending on 4 conditions」.. 

1. Not Read 
2. Normal Read 
3. Read and Keep 
4. Peek and Read 


Condition 1 (Not read): If you set a 「TempData」 inside your action and if you do not read it in your view, then 「TempData」 will be persisted for the next request. 

Condition 2 (Normal Read): If you read the 「TempData」 normally like the below code, it will not persist for the next request. 

stringstr = TempData["MyData"]; 
Even if you are displaying, it’s a normal read like the code below: 


@TempData["MyData"]; 
Condition 3 (Read and Keep): If you read the 「TempData」 and call the 「Keep」 method, it will be persisted. 


@TempData["MyData"]; 
TempData.Keep("MyData"); 
Condition 4 (Peek and Read): If you read 「TempData」 by using the 「Peek」 method, it will persist for the next request. 


stringstr = TempData.Peek("Td").ToString(); 

乾杯! !

+0

所以它就像請求1創建'TempData',請求2 3 4我不讀取它,而是調用其他Action,然後在請求5上使用'TempData'還在嗎? –

+0

如果你沒有閱讀,它會提供第5個請求。 –

+1

好的,非常感謝:D –

1
TempData["myTempData"] 

1)TempData的持久性只在行動對行動,假設動作1調用你將數據存儲到的TempData [「myTempData」],那麼你需要在動作2即會DEFINITY訪問數據堅持。

2)如果要然後存儲在TempData的數據[ 「myTempData」]對每一個行動第一TempData的[ 「myTempData」]值分配給TempData的[ 「myTempData」]然後在每個動作中使用它,直到你將其強制刪除。

希望查詢能夠解決。

+0

謝謝:D我會考慮使用你的解決方案:D –