---
title: "Define Viewbag in MVC?"  
description: "Define Viewbag in MVC?"  
author: "Anonymous User"  
published: 2020-01-27  
updated: 2020-01-27  
canonical: https://www.mindstick.com/forum/155739/define-viewbag-in-mvc  
category: "asp.net mvc"  
tags: ["asp.net mvc"]  
reading_time: 2 minutes  

---

# Define Viewbag in MVC?

[Explain me](https://www.mindstick.com/forum/34220/can-anyone-explain-me-about-off-page-activity) what is [Viewbag](https://www.mindstick.com/forum/155742/what-is-similarities-and-differentiate-between-viewdata-and-viewbag) in [MVC](https://www.mindstick.com/forum/155803/define-cache-profile-in-mvc) with example.

## Replies

### Reply by Nishi Tiwari

**ViewBag** is defined as to pass data from Controller Action to view to render the data that is being passed. Now we can pass data between **[Controller Action and View](https://www.mindstick.com/forum/155740/define-viewdata-in-mvc)** either by using **ViewBag or ViewData.**

**ViewBag:** It is type of Dynamic object, which means we can add new fields to viewbag dynamically and access these fields in the View. We need to initialize the object of viewbag at the time of creating new fields.

e.g: 1. Creating ViewBag: ViewBag.FirstName="John";

2. Accessing View: @ViewBag.FirstName.

## Example

In this example, we are implementing ViewBag property.

## Controller

```
using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace ViewBagExample.Controllers
{
    public class ViewBagController : Controller
    {
        // GET: ViewBag
        public ActionResult Index()
        {
            List<string> Courses = new List<string>();
            Courses.Add("J2SE");
            Courses.Add("J2EE");
            Courses.Add("Spring");
            Courses.Add("Hibernates");
            ViewBag.Courses = Courses;
            return View();
        }
    }
}
```

## View

```
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h2>List of Courses</h2>
    <ul>
        @{
            foreach (var Courses in ViewBag.Courses)
            {
                <li> @Courses</li>
            }
        }
    </ul>
</body>
</html>
```

## Output:

The Index file produces the following output to the browser.

![Define Viewbag in MVC?](https://www.mindstick.com/mindstickforums/77b80018-93d8-45f7-8140-efff83dd4bcb/images/94b8d12d-7719-41e5-ad14-37d7bff50e4a.png)


---

Original Source: https://www.mindstick.com/forum/155739/define-viewbag-in-mvc

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
