ViewData and ViewBag in MVC
What is the need for a ViewData and ViewBag?
Whenever a web browser sends a HTTP request, MVC framework uses Routing Engine to map the incoming requests to an action method on a controller class to process it. MVC applications are responsible for handling user requests, making interactions and executing the application logic. When it comes to rendering this logic in the user interface, say like HTML, JSON or whatever, controllers typically have to work with views. Views encapsulate the presentation logic from the controller’s application logic. ViewData and ViewBag are introduced in MVC to help transfer data between controller and view. In MVC we do not have the concept of ViewState which is the biggest pain with session handling in asp.net web pages.
What is ViewData?
View Data is nothing but a dictionary inherited from VIewPage base class of MVC that inherits from system.web.UI.Page class of system.web. When we say it is a dictionary, it accepts values as key value pairs.
ViewData[“ReturnUrl”] = returnUrl;
Here the ReturnUrl is the key and the reutrnUrl is the value.
How to consume it in View?
NOTE: We need to externally cast ViewData if we need to apply some logic like looping.
What is ViewBag?
Yeah. Like the blue dressed girl said, we don’t have to take care of casting viewdata and no need of creating viewmodel to pass strongly typed viewdata if we use viewbag. Most of the recent applications developed with MVC 3.0 and above, use ViewBag.
Inside the controller, the syntax goes like this
ViewBag.ReturnUrl = returnUrl;
The view will be like this
ViewBag is considered a syntactic sugar over viewdata, maybe the advanced version of viewdata.
Tempdata is used to transfer data from one controller to another.