If I redirect to a new page passing TempData to initialise the page it works fine, however if the user presses the refresh button in their browser the TempData is no-longer available.
Given this, is there any situation where TempData could be used reliably?
Or any way to remove or mitigate the problem of users refreshing?
You should write
TempData.Keep("nameofthedata");
in your controller, then it will keep that data in refresh situations too.
In MVC 1, yes, temp data is lost after the next request after you store a key.
With MVC 2 however, the temp data is lost after the first attempt to access it.
You can always use Session, which TempData uses anyway, to solve the temp data loss issue your having.
From the MVC 2 Beta Release Notes:
TempDataDictionary Improvements
The behavior of the TempDataDictionary class has been changed slightly to address scenarios where temp data was either removed prematurely or persisted longer than necessary. For example, in cases where temp data was read in the same request in which it was set, the temp data was persisting for the next request even though the intent was to remove it. In other cases, temp data was not persisted across multiple consecutive redirects.
To address these scenarios, the TempDataDictionary class was changed so that all the keys survive indefinitely until the key is read from the TempDataDictionary object. The Keep method was added to TempDataDictionary to let you indicate that the value should not be removed after reading. The RedirectToActionResult is an example where the Keep method is called in order to retain all the keys for the next request.
You can also look directly in the MVC 2 source to see these changes:
MVC 1:
public object this[string key] {
get {
object value;
if (TryGetValue(key, out value)) {
return value;
}
return null;
}
set {
_data[key] = value;
_modifiedKeys.Add(key);
}
}
MVC 2:
public object this[string key] {
get {
object value;
if (TryGetValue(key, out value)) {
_initialKeys.Remove(key);
return value;
}
return null;
}
set {
_data[key] = value;
_initialKeys.Add(key);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With