ASP.NET MVC - ViewData

In the previous tutorial, we discussed ViewBag and it uses in moving data from the controller to the view. Here we will discuss ViewData, another dynamic container for transferring chunks of data from the controller to the views.

ViewData is similar to ViewBag. It is used for transferring data from Controller to View. Unlike ViewBag, ViewData is a dictionary which can contain key-value pairs where each key must be string.

asp.net transferring data from Controller to View

The snapshot below illustrates the operation of a ViewData in an MVC application.

Like ViewBag, ViewData also transfers data only from controller to view, and never vice-versa. Also, on redirect, data stored in the ViewData gets lost.

In the following example we will demonstrates how to transfer data from controller to view using ViewData.

Example: ViewData in Action method

public ActionResult Index()
    IList<Activity> activityList = new List<Activity>() { 
    new Activity(){ ID=1, ActivityName="Write C#", Time = 21 },
    new Activity(){ ID=2, ActivityName="Read Poems",Time = 25},
    new Activity(){ ID=3, ActivityName="Play Games", Time = 20 },                };
    ViewData["activities"] = activityList;
    return View();

In the above example, we have added an activity list with the key "activities" in the ViewData dictionary. So now, the activity list can be accessed in a view as shown below.

Example: Access ViewData in a Razor View

@foreach (var act in ViewData["activities"] as IList<Activity>)
        @act. ActivityName

Note: When using ViewData, Values must be cast to the appropriate data type unlike ViewBag where casting isn?t needed.

New key value pairs can also be added to the ViewData using the format illustrated in the code snippet below:

Example: Add KeyValuePair in ViewData

public ActionResult Index()
    ViewData.Add("Id", 1);
    ViewData.Add(new KeyValuePair<string, object> ("Name", "Vitalis"));
    ViewData.Add(new KeyValuePair<string, object> ("Time", 50));
    return View();

Internally, ViewData and ViewBag both use the same dictionary. Hence you cannot give an exert property name to ViewData and ViewBag, otherwise it will throw a runtime exception.

Example: Assigning ViewBag and ViewData with the same property name

public ActionResult Index()
    ViewBag.Id = 1;
    ViewData.Add("Id", 1); // throw runtime exception as it already has "Id" key
    return View();

Inviting useful, relevant, well-written and unique guest posts