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.
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
We will access ViewBag in our Index View as follows.
it helped me
Thanks it also helped me
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.