Introduction:

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

Description:

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">
        <tr>
            <td colspan="3"><h2>Mvc Application Use ViewBag</h2></td>
        </tr>
         <tr>
             <th>Id</th>
             <th>Name</th>
             <th>Age</th>
         </tr>
    @foreach(var item in ViewBag.users )
    {
    <tr>
        <td>@item.id</td>
        <td>@item.Name</td>
        <td>@item.Age</td>
    </tr>
    }
    <tr>
         <td colspan="2">Total Users</td>
         <td >@ViewBag.count</td>
     </tr>
    </table>
 
<style>
    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;
        }
</style>

 

OutPut:


ViewBag in ASP.NET MVC


I hope this article will help to you.


0 comments


Leave a comment

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

You may also like