Free Web Development Online Tutorials, Learn to Code
Learn Asp.net MVC C#, Asp.net MVC Tutorial for Beginners, Model View Controller

How to use ViewBag in Asp.net MVC

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";

How to get viewbag value in view from controller! will 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