In this tutorial we will learn what is ViewBag in MVC or How to use ViewBag in MVC with Example.


ASP.NET MVC ViewBag is use for passing data from controller to view. ViewBag is a dynamic property (dynamic keyword which is introduced in .net framework 4.0). It doesn’t require typecasting for complex data type.

Example: Set ViewBag in Action method 

using MvcApplication1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
    public class HomeController : Controller
    {              public ActionResult Index()
            IList<User> UserList = new List<User>() {
                    new User(){ id=1, Name="Mack", Age =21 },
                    new User(){ id=2, Name="Mark", Age =25 },
                    new User(){ id=3, Name="Johan", Age =20 },
                    new User(){ id=4, Name="Brain", Age =31 },
                    new User(){ id=5, Name="Myank", Age =19 }
            ViewBag.users= UserList;
       ViewBag.count= UserList.Count;
            return View();
    }     }


Example: Acess ViewBag in a View 

@using MvcApplication1.Models
 <table border="0">
            <td colspan="3"><h2>Mvc Application Use ViewBag</h2></td>
    @foreach(var item in ViewBag.users )
         <td colspan="2">Total Users</td>
         <td >@ViewBag.count</td>
    table {
        width: 500px;
        margin: 0 auto;
    table, th, td {
        border: 1px solid grey;
        border-collapse: collapse;
        padding: 5px;
        table tr:nth-child(odd) {
            background-color: #ccc;
        table tr:nth-child(even) {
            background-color: #ffffff;



ViewBag in ASP.NET MVC

I hope this article will help to you.

Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like