Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing data in HttpContext.Current.Items vs ViewData

When is it appropriate to store data in 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?

like image 750
Petrus Theron Avatar asked Apr 06 '10 18:04

Petrus Theron


People also ask

When should I use HttpContext items?

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.

What is the difference between session and HttpContext current session?

There is no difference. The getter for Page. Session returns the context session.

Is HttpContext current items thread safe?

The HttpContext is NOT thread safe, accessing it from multiple threads can result in exceptions, data corruption and generally unpredictable results.

What is the purpose of ViewData?

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.


1 Answers

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.

like image 188
womp Avatar answered Oct 15 '22 20:10

womp