What is ViewBag

In my last article I explain how to send data from view to controller using ViewData. In this article we will discuss how we can send data using ViewBag. ViewBag used dynamic property which introduced in C# 4.0.

It is actually a dynamic ViewData Dictionary so you can say that it’s just a wrapper around ViewData.

ViewBag Example

Create a controller name Home and create view name Index. In this view create a list of type string in which stores the Department Name.

Code of Home Controller

		
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication5.Controllers
{
    public class HomeController : Controller
    {
       
        public ActionResult Index()
        {
            List<string> dept = new List<string>()
            {"HR","Sales","Developer"};

            ViewBag.dept_name = dept;
            return View();
        }

    }
}


		

Code of Index View

In this example we create dynamic property named dept_name. Now use this ViewBag in View

		
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        Employee Departments are:-<br />
        @foreach (string dept in ViewBag.dept_name)
        { 
        
            <p><b>@dept</b></p>
        
        }
    </div>
</body>
</html>

		
		

As you can see that we need not to perform the type casting while working with ViewBag.

The output of this code will be as follows:-

		
		ViewBag in MVC
		Figure 1
		
		

Email Address

For any query you can mail me at info@techaltum.com