When should I use one versus the other? I want to cache a certain object on startup and reuse around the application. Which sounds like the better solution (ViewData or Session)?
ViewBag will be slower than ViewData; but probably not enough to warrant concern.
TempData is ideal for short-lived things like displaying validation errors or other messages that we don't need to persist for longer than a single request. Session is ideal choice when we need to persist data for extended periods of time i.e. it is used to store data which is required throughout user session.
All three objects are available as properties of both the view and controller. As a rule of thumb, you'll use the ViewData, ViewBag, and TempData objects for the purposes of transporting small amounts of data from and to specific locations (e.g., controller to view or between views).
ViewData
is a per-request object used to send information from the controller to the view.
Each action invocation gets its own ViewData; the ViewData doesn't last beyond the view.
Session State is a per-user storage container which allows you to store data for a specific user session (identified by a cookie)
If you want to share a global object, you should probably make it a singleton (in a static
property) or put it in Application state.
Make sure that it's thread-safe. (Or use a [ThreadStatic]
field carefully)
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