What is ViewBag in ASP.Net MVC3?

ViewBag one of the feature of ASP.Net MVC 3.In classic web application we have different methods for passing data from one page to the other.But unluckily none of them works for ASP.Net MVC 3. Here comes the importance of ViewBag.

What is ViewBag ?

ViewBag is one of the property of both ASP.Net Controller and View.

Why ViewBag ?

A View Bag Allows developer to pass data from Controller to View or between views.

How ?

We can pass data from Controller to View by adding in to ViewBag Object.


1.Its dynamic compared to its ViewData counterpart.
2.It works well with small aggregate of data.
3.It allows to add dynamic properties to it which makes it a very versatile.


1.If you want to work with larger amounts of data, reporting data, create dashboards, or work with multiple disparate sources of data ViewData is not a good choice.


Let us see how to add data to ViewBag.

public class HomeController : Controller
public ActionResult Index()
ViewBag.Message = "Hello World!"; // Adding to ViewBag
return View();

We will access ViewBag in our Index View as follows.




Guest Author: srinivas26 Mar 2013

it helped me

Guest Author: ashok27 May 2013

Thanks it also helped me

Guest Author: Jeff03 Feb 2014

Do you know why setting a ViewBag property, eg: ViewBag.Title, triggers this error?:
"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException occurred. Message='System.Dynamic.DynamicObject' does not contain a definition for 'Title'"
I've found nothing that really answers this. Only suggestions to uncheck the CLR exceptions while debugging. For anyone just browsing the site, they'd probably never know the error is getting thrown, because the site works and the data stored in the ViewBag properties is displayed.

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: