#64 ViewData and ViewBag

They are responsible for passing data from controller to view.

ViewData:

1.It is a dictionary,which holds keys as strings.

2.It can be used to store any complex data.

3.They have to casted/Null check has to be made in view to avoid Error.

ViewBag:

1.They use dynamic property listed with C#4.0

2.They do not require type casting of complex objects.


/*Controller*/

public ActionResult Index()
{
ViewData["Sample"] = "Sample ViewData";
ViewBag.Hello = "Sample ViewBag";
return View();
}

They are accessed in view with respective Name declared in controller

/*View*/

@ViewBag.Hello
@ViewData["Sample"]