Introduction:

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


Description:

 ASP.NET MVC ViewData is similar to ViewBag, ViewData 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">
        <tr>
            <td colspan="3"><h2>Mvc Application Use ViewData </h2></td>
        </tr>
         <tr>
             <th>Id</th>
             <th>Name</th>
             <th>Age</th>
         </tr>
@foreach (var item in ViewData["users"] as List<User>)    {
    <tr>
        <td>@item.id</td>
        <td>@item.Name</td>
        <td>@item.Age</td>
    </tr>
    }
    <tr>
         <td colspan="2">Total Users</td>
         <td> @ViewData["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:


ViewData in ASP.NET MVC


Thanks.

0 comments


Leave a comment

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

You may also like