views:

419

answers:

1

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?

+5  A: 

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.

womp
Great answer. I realize I am more interested in ViewData than Session, so I edited my question as such. Thank you for the clarification on RenderPartial. Will HttpContext.Current.Items persist between redirects?
FreshCode
No - a redirect actually returns a 302 response to the browser, which then issues a new request to the server. However, you might look at using the TempData dictionary if you're just looking to persist data until the next redirection. http://blogs.teamb.com/craigstuntz/2009/01/23/37947/
womp