Is ViewBag and ViewData also part of state management in asp.net mvc?

Jitender Kumar picture Jitender Kumar · Jun 1, 2013 · Viewed 10.6k times · Source

Can somebody please tell me that whether ViewData and ViewBag are also part of asp.net mvc state management or not? Thanks

Answer

Andy Brown picture Andy Brown · Jun 1, 2013

ViewBag and ViewData do not store state, but they can pass it to views to be rendered and stored.

What are ViewBag and ViewData?

ViewBag and ViewData are not state persistence mechanisms, but I believe they are part of State Management: they are mechanisms for passing data to a page which can then be persisted as state in the generated html. In this way they are part of the lifecycle of state, as they allow you to store state in your client side html using helpers such as @Html.HiddenFor or @Html.ActionLink.

In my answer to "storing a js value from 1 ActionResult to use in another ActionResult" I talk about how ViewBag and ViewData can be used to store state in the client html, and what the various options for state storage are.

As for what ViewBag is, it's actually a dynamic way of accessing ViewData, so ViewBag.MyItem = "foo"; and var valueEqualsFoo = ViewData["MyItem"]; will set and return the same string and can be interchanged.

What are they similar to?

ViewBag, ViewData are most closely connected to a View Model in an Action, where the model is passed to a View inside the Action using return View(viewModel);: all three techniques pass the state in memory into the html where it is sent to the client, to any intermediate caches, and "persisted" away from your server.

In a similar way, when a query string in a url is sent to a server in an http request it is a method of passing state, the actual state store is the <a href="urlwithquerystring">...</a> anchor in the html. Restful URLs, and bodies for POST ajax requests, are the same in their definition and behaviour. ViewBag/Data pass the state from the Action to the html, which is passed to the client and stored, the query string or restful url then pass the state back to the server for use in the next Action invocation.

When should I use them?

It is hard to check for dynamic properties with a misspelling in your Razor code; it is easy to check if a property exists on a strongly typed view model. Therefore I believe you should use them very rarely. In my opinion it is preferable to create strongly typed view models rather than use ViewBag or ViewData. They might be fine for a quick and dirty solution, but those things tend to create Technical Debt. ViewBag is possibly ok for setting the page title.

Strongly typed View Models:

  • make it easier to use mapping with frameworks like automapper;
  • make views more testable; and
  • make it easier to create different views for different devices where you pass the same model to each view

What are my options for state storage?

I said it here, and I'll say it again: There used to be at least Nine Options for Managing Persistent User State in ASP.NET, and many of those still apply in MVC. They all have different uses depending on how the state should be used. Generally server side code that is as stateless as possible is easier to test and debug.

  • Client side storage includes:
    • Entities passed back in the html result, and turned into:
      • Input fields
      • Hidden Fields
      • Javascript variables for use in ajax request POST bodies
      • Query string values, and paths in URLs (e.g. Restful URLs like /Product/1)
    • Older ASP.NET techniques that keep state in hidden html fields such as ViewState
    • Cookies
    • Html5 techniques such as Local Storage
    • Anti forgery tokens generated to prevent XSRF
  • Server side storage (directly related to ASP.NET and ASP.NET MVC):
    • Session (available through the Controller's Session property
    • Cache (available through the Controller's Cache property)
    • TempData
    • HttpContext["item key"]
    • Application (available through the Controller's HttpContext property as HttpContext.Application)
    • Web.config and Machine.config files (yes, these also hold state, it is just application wide) and therefore the WebConfigurationManager.AppSettings dictionary.
  • Server side storage (other):
    • Databases whether SQL or NOSQL
    • File storage
    • Message Queues such as WASB

Footnotes:

We now have easy to use tools for responsive design which we can use when appropriate, but it is not always suitable: some views need to look entirely different on mobile but still use the same viewmodel as the large screen site.