ViewBag, ViewData and TempData in MVC 3

ViewData, is a dictionary object which is a derivative of the ViewDataDictionary class. It allows you to pass data to the view as key value pairs. In the view you will need to cast the value pairs to whatever type you need.

ViewBag, allows you to pass dynamic type objects to the view. It is a wrapper around the ViewData object. No casting is required.

Both ViewData & ViewBag are used to passing data between controllers and views.

Eg.

Controller,

ViewData[“Name”] = “Hello World”;

ViewBag.Name = “Hello World”;

View,

@{ var name = ViewData[“Name”] as string; }

@{ var name = ViewBag.Name; }

TempData, is to pass data between two requests. It only works when you know what the next request will be and you can access the TempData from the subsequent request’s view.

Eg.

Controller,

TempData[“Name”] = “Hello World”;

return new RedirectResult(@“~\SubsequentView\”);

View,

@{ TempData[“Name”] as string; }

Advertisements