Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

ViewBag in Asp.net MVC, MVC Tutorial

What is ViewBag in Asp.Net MVC?

ViewBag a dynamic object property, that allows you to hold any type of data and share them between the controller and view within ASP.NET MVC application. though it has some limitation, and there are other options also available, but ViewBag is really easy to use.
Let's take a look at few realtime example.

Namespace: System.Web.Mvc
Assembly: System.Web.Mvc (in System.Web.Mvc.dll)
C# Syntax of ViewBag
public object ViewBag { get; }

You can add property then can assign value to ViewBag, here is an example of how you can write ViewBag at Controller
ViewBag.PageTtitle="I am learning ViewBag at WebTrainingRoom";

Now to retrieve the property at View(razor)
<h1>@ViewBag.PageTtitle</h1>

You also can add any custom object, list, array in ViewBag, and cast them back in right data type in View. here is an example.
public ActionResult actionviewbag()
{
ArrayList alColors = new ArrayList();
alColors.Add("Red");
alColors.Add("Green");
alColors.Add("Yellow");
alColors.Add("White");
alColors.Add("Orange");
alColors.Add("Blue");
alColors.Add("Black");

ViewBag.Colors = alColors;
return View();
}

Now in View (razor) you can access the ViewBag property this way.
@{
ArrayList _colors = ViewBag.Colors as ArrayList;
foreach (string color in _colors)
{
<div>@color</div>
}
}

Ideal use of ViewBag when you have small amount of data to be transferred from controller to view, ViewBag allows you to create a runtime property and assign the value

Things to remember when using ViewBag
  • ViewBag cannot hold value if you move out of current page, it becomes null
  • There is no intellisense that will get you the property name you have specified in ViewBag, So you have to remember the exact name while accessing it, also the type,
    for example while accesing the above ArrayList _colors = ViewBag.Colors as ArrayList;
    we have converted to ArrayList, similarly you have to remember the type


You may also learn about ViewData and TempData in Asp.net MVC, or read difference among ViewBag, ViewData and Tempdata
Comment
Name Email Website
Subscribe
 
ViewBag in Asp.net MVC Tutorial

Group Training