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 is dictionary type which stores data in object format. So we need to perform type casting at the time of data retrieval.

For example:-
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>()

            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>

    <meta name="viewport" content="width=device-width" />
        Employee Departments are:-<br />
        @foreach (string dept in (List<string>) ViewData["dept_name"])


As you can see that to traverse this ViewData I have to perform the type casting.

The output of this code will be as follows:-

		if-else in MVC using Rzor
		Figure 1

Email Address

For any query you can mail me at info@techaltum.com