ViewData in MVC

ViewData is similar to ViewBag. We use to  transfer the data from Controller to View.

ViewData is a dictionary which can contain key-value pairs where each key must be string.

The following figure illustrates the ViewData.

ViewData only transfers data from controller to view, not vice-versa and It is valid only during the current request.

The following example demonstrates how to transfer data from controller to view using ViewData.

Example: ViewData in Action method

public ActionResult Index()
{
    IList<Student> studentList = new List<Student>();
    studentList.Add(new Student(){ StudentName = "Bill" });
    studentList.Add(new Student(){ StudentName = "Steve" });
    studentList.Add(new Student(){ StudentName = "Ram" });

    ViewData["students"] = studentList;
  
    return View();
}

In the above example, we have added a student list with the key “students” in the ViewData dictionary. So now, the student list can be accessed in a view as shown below.

Example: Access ViewData in a Razor View

<ul>
@foreach (var std in ViewData["students"] as IList<Student>)
{
    <li>
        @std.StudentName
    </li>
}
</ul>

Notice that we need to cast  the ViewData values to the appropriate data type.

We can also add a KeyValuePair into ViewData as shown below.

Example: Adding KeyValuePair in ViewData

public ActionResult Index()
{
    ViewData.Add("Id", 1);
    ViewData.Add(new KeyValuePair<string, object>("Name", "Bill"));
    ViewData.Add(new KeyValuePair<string, object>("Age", 20));

    return View();
}

ViewData and ViewBag both use the same dictionary internally. So we cannot have ViewData Key matches with the property name of ViewBag, otherwise it will throw a runtime exception.

Example: ViewBag and ViewData

public ActionResult Index()
{
    ViewBag.Id = 1;

    ViewData.Add("Id", 1); // throw runtime exception as it already has "Id" key
    ViewData.Add(new KeyValuePair<string, object>("Name", "Bill"));
    ViewData.Add(new KeyValuePair<string, object>("Age", 20));

    return View();
}

4 Replies to “ViewData in MVC”

    1. Sure Lelio Vieira Carneiro, Thanks for your support. We are from Avent ITS Solutions offers niche IT professional services on C#, ASP.NET, WCF, SQL Server, SharePoint, and web CMS including CMS based on .NET. We have a proven record in providing C#, ASP.NET, SQL Server-based services to ourflagship client in North America since 2014.

Leave a Reply

Your email address will not be published. Required fields are marked *