In this tutorial we will learn what is ViewData in MVC or How to use ViewData in MVC with Example.


ASP.NET MVC ViewData is similar to ViewBagViewData is use for passing data from controller to view. ViewData is a dictionary object that is derived from ViewDataDictionary class .It require typecasting for complex data type.

Example: Set ViewData 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 }
       ViewData["users"] =UserList;
       ViewData["count"] = UserList.Count;
            return View();
    }     }



Example: Acess ViewData in a View

@using MvcApplication1.Models
 <table border="0">
            <td colspan="3"><h2>Mvc Application Use ViewData </h2></td>
@foreach (var item in ViewData["users"] as List<User>)    {
         <td colspan="2">Total Users</td>
         <td> @ViewData["count"] </td>
    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;



ViewData in ASP.NET MVC


Leave a comment

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

You may also like