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. Advantage
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. Disadvantage
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. Example
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.
@{
}
it helped me
thanks