Free Web Development Online Tutorials, Learn to Code
Learn Asp.net MVC C#, Asp.net MVC Tutorial for Beginners, Model View Controller

How to use ViewData in Asp.net MVC Razor

What is ViewData in Asp.Net MVC?

ViewData is a dictionary object, which can contain key-value pairs, useful for transferring data from controller to view in ASP.NET MVC Application, In ViewData each key must be string type.
Let's take a look at few realtime example.

C# Syntax of ViewData
 public ViewDataDictionary ViewData { get; set; }

You can add key-value pair to ViewData, here is an example of how you can write ViewData at Controller

ViewData["PageTtitle"]="I am learning ViewData at WebTrainingRoom";

How to access viewdata in razor view from controller, Here is how you can retrieve the property at View(razor)

<h1>@ViewData["PageTtitle"]</h1>

You also can add any custom object, list, array in ViewData, and cast them back in right data type in View. here is an example.

public ActionResult actionViewData()
{
ArrayList alColors = new ArrayList();
alColors.Add("Red");
alColors.Add("Green");
alColors.Add("Yellow");
alColors.Add("White");
alColors.Add("Orange"); alColors.Add("Blue");
alColors.Add("Black");
ViewData["Colors"] = alColors;
    return View();
}

Now in View (razor) you can access the ViewData property this way.

@{
ArrayList _colors = ViewData["Colors"] as ArrayList;
foreach (string color in _colors)
{
<div>@color</div>
    }
}

Ideal use of ViewData when you have small amount of dictionary data (with key-value pair) to be transferred from controller to view.
Things to remember when using ViewData

  • In one action (page) if you are using ViewBag and ViewData both, make sure their key should not match, because ViewBag and ViewData both use the same dictionary internally

    for example, if you write in your controller
    ViewData["student"] = "Anisha";                            
    ViewBag.student = "Arundhuti";
    

    then access the ViewData @ViewData["student"] ,this will print "Arundhuti", not "Anisha", because the key value is overwritten

  • ViewData cannot hold value if you move out of current page, it becomes null
  • There is no intellisense that will get you the key name you have specified in ViewData, So you have to remember the exact name while accessing it, also the type,

    for example ArrayList _colors = ViewData["Colors"] as ArrayList;

    we have converted to ArrayList, so you have to remember both key name and type

You may also learn about ViewBag and TempData in Asp.net MVC, or read difference among ViewBag, ViewData and Tempdata

Comment
Name
Email
Website
Subscribe
 
ViewData in Asp.net MVC