HttpContext.Current.Items[...]
vs storing data in ViewData[...]
?I'm trying to figure out the best practices for storing data in this collection and I'm not sure if it's safe to store user-specific data in HttpContext.Current.Items
.
One use-case is passing down user credits from a base controller's OnActionExecuting(...)
to be used in Controller
calculations and for display in Views
; I know I should be using ViewData
for this, but I've had some inconsistent results with nested partial views.
Would it be correct to say that HttpContext.Current.Items[...]
is to Controllers
like ViewData[...]
is to Views?
Similarly, you use HTTPContext Items collection when you are sharing the same information across the different instance based on the user request and that request could be changed for a different request.
There is no difference. The getter for Page. Session returns the context session.
The HttpContext is NOT thread safe, accessing it from multiple threads can result in exceptions, data corruption and generally unpredictable results.
In MVC, when we want to transfer the data from the controller to view, we use ViewData. It is a dictionary type that stores the data internally. ViewData contains key-value pairs which means each key must be a string in a dictionary.
HttpContext.Current.Items
only lasts for the duration of the request, but it is global to everything in that request.
Session obviously lasts for the entirety of the user's session, and persists between requests.
You should be able to figure out which one you need to use based on those criteria alone. Using HttpContext.Current.Items
is not something I would recommend as it tends to be a kind of "global variable", and magic key strings tend to get involved, but sometimes you really do need to use it.
Additionally, although your comparison between .Items and ViewData is pretty apt, .Items differs from the way that ViewData behaves, because every View involved in the request (partial or otherwise) gets their own copy of ViewData.
The behaviour difference is clear when you do a RenderPartial
and try to add something to ViewData - when you go back up to the parent view, the item is not there.
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