Join Class

ViewBag in MVC

What is ViewBag in Asp.Net MVC?, How to use ViewBag in MVC, learn with example.

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 in .Net MVC

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)


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("Orange"); alColors.Add("Blue");
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)

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 MVC, or read difference among ViewBag, ViewData and Tempdata

ViewBag in MVC
Aspnet MVC Training MVC tutorials, learn model view controllers with c#, develop database driven web application using MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Core Tutorial