articles

Home / DeveloperSection / Articles / ViewBag in ASP.NET MVC

ViewBag in ASP.NET MVC

Chris Anderson20413 08-Oct-2011

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>();
            hobby.Add("Cricket");
            hobby.Add("Football");
            hobby.Add("Chess");

            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>
 
<html>
<head runat="server">
    <title>Index</title>
</head>
<body>
    <div>
            <!-- Retreiving Dynamic properties -->
        <p>
            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:
        </p>
        <ul>
            <% foreach (var hobby in ViewBag.Hobbies) { %>
            <li>
                <font color="blue"><%: hobby %></font>
            </li>
            <% } %>
        </ul>
    </div>
</body>
</html>

 

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

ViewBag in ASP.NET MVC


Updated 07-Sep-2019
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By