Home > DeveloperSection > Beginner > ViewBag in ASP.NET MVC

ViewBag in ASP.NET MVC

0 Comment(s)
 14411  View(s)
Rate this:

ViewBag in ASP.NET MVC

ViewBag is a property of a Controller class that we generally used to share data between Controller and View and. ViewBag objects is wrapper around ViewData that is used to create dynamic properties for ViewBag.
The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.

How to use ViewBag?

Here I am explaining how to create dynamic ViewBag properties and displaying properties information in View.

In Controller class we created a several dynamic ViewBag properties i.e. Hobbies, Username, Age, and MaritalStatus that stores user information. For a hobby I use a List class from System.Collections.Generic because a user can have various hobbies.

using System.Web.Mvc;

using System.Collections.Generic;


namespace ViewBag.Controllers


    public class HomeController : Controller



        public ActionResult Index()


            List<string> hobby = new List<string>();





            ViewBag.Hobbies = hobby; //hobby is List

            ViewBag.UserName = "Rohit ";

            ViewBag.Age = 19;

            ViewBag.MaritalStatus = "Unmarried";

            return View();






In the above View we are accessing various dynamic ViewBag properties that we are created in Controller class.


<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>


<!DOCTYPE html>



<head runat="server">





            <!-- Retreiving Dynamic properties -->


            My name is <b><%: ViewBag.UserName %></b>,

            I am<b><%: ViewBag.Age %></b> years old.

            I am <b><%: ViewBag.MaritalStatus %></b>.

            <br /><br />   

            I like the following things:



            <% foreach (var hobby in ViewBag.Hobbies) { %>


                <font color="blue"><%: hobby %></font>


            <% } %>






When you run your MVC application it displays the output like below:

ViewBag in ASP.NET MVC

Don't want to miss updates? Please click the below button!

Follow MindStick