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.



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

ViewBag.Name = “Hello World”;


@{ 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.



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

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


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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s