Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC does browser refresh make TempData useless?

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?

like image 440
Myster Avatar asked Apr 15 '10 01:04

Myster


2 Answers

You should write

TempData.Keep("nameofthedata");

in your controller, then it will keep that data in refresh situations too.

like image 61
cemsazara Avatar answered Sep 19 '22 09:09

cemsazara


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);
        }
    }
like image 32
John Farrell Avatar answered Sep 20 '22 09:09

John Farrell