ViewData in MVC



What is ViewData

ViewData is used to access data from controller to view. ViewData stores data as key-value format. ViewData type is ViewDataDictionary. Internal declaration of ViewData is:-
public ViewDataDictionary ViewData { get; set; }

Syntax of ViewData

ViewData[“key”]=value;
Viewdata is dictionary type which stores data in object format. So we need to perform type casting at the time of data retrieval.

Example of ViewData

Create a controller name Home and create view name Index. In this view create a list of type string in which stores the Department Name.

Code of Home Controller

  
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication5.Controllers
{
    public class HomeController : Controller
    {
       
        public ActionResult Index()
        {
            List<string> dept = new List<string>()
            {"HR","Sales","Developer"};

            ViewData["dept_name"] = dept;
            return View();
        }

    }
}    

Code of Index View

Now use this ViewData in your View in the following manner:-
  
  
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        Employee Departments are:-<br />
        @foreach (string dept in (List<string>) ViewData["dept_name"])
        { 
        
            <p><b>@dept</b></p>
        
        }
    </div>
</body>
</html>    
As you can see that to traverse this ViewData I have to perform the type casting.

No comments:

Post a Comment