Home » ASP » ASP.MVC » TempData why you should use bracket instead of .Add

TempData why you should use bracket instead of .Add

TempDataDictionary (TempData is of type of TempDataDictionary) is useful if you need to keep you data between redirection. I have see some case of error with programmer who use the TempData with the Add method.

First the Add method won’t let you add more than 1 same key. This mean that it will crash if you write:


You will tell me why someone will do this, well, in the scenario of redirection, which should occur if you are using TempData instead of ViewBag you may comeback in the same path of code that the user set the data. In this case, the value are set twice cause the TempData in a redirection keep its values.

So, you can add some validation with the ContainsKey method.


Second, this solve the problem but create overwhelming code for a simple task. The solution in my opinion is to simply use the bracket overload of the TempDataDictionary.

TempData["key1"] = "value1";

The code is shorter, cleaner and do what we want. It set the value and if it’s a redirection to the same code who has set the value this one will just reset the same value. That’s it! Simple and clean.

If you are curious about the bracket code, here is the source code of the TempData for the property [].

private Dictionary<string, object> _data;
private HashSet<string> _initialKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
public object this[string key] 
         object value;
         if (TryGetValue(key, out value)) 
             return value;
         return null; 
        _data[key] = value; 

Of course, the real question now is why does this code has redirection that double set this value, but this is another story.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.