ViewData is a dictionary used in C# MVC to pass data from the controller to the view. This feature was first introduced in MVC 1.0. To use this tag, the post must be using C#, MVC, and must be in regards to the use of ViewData.
ViewData is one of the alternate ways to pass data from controller to view without using the Model.
Syntax
ViewData is a dictionary that is set in the controller and is read in the view. For example:
Controller
public ActionResult ViewTest()
{
ViewData["Content"] = "some text";
return View();
}
View
<div>
ViewData content: @ViewData["Content"]
</div>
Result
<div>
ViewData content: some text
</div>
ViewData only accepts string as keys, otherwise it will generate an error alert. So the following is not possible:
ViewData[1] = "some text"; //cannot convert from 'int' to 'string'
As far as a value, these are totally legal:
ViewData["Content"] = 1; //prints 1
ViewData["Content"] = true; //prints True
ViewData["Content"] = DateTime.Now; //prints the date (i.e. 4/16/2019 9:50:05 AM)
If the value is a object, you must cast the ViewData in the view in order to access the property to read from:
Controller
public ActionResult ViewTest()
{
ViewData["Content"] = new SomeClass
{
SomeProp = "some text"
};
return View();
}
View
<div>
@{
var viewDataContent = (SomeClass) ViewData["Content"];
}
ViewData content: @viewDataContent.SomeProp
</div>
Because you must cast an object, you cannot use an anonymous type as a value. While a workaround is possible, it's not recommended as it results in ugly code that is difficult to maintain.
Life
The life of ViewData is only for the current request. Once the request is done, ViewData expires. This means that if ViewData is set before a redirect, it will be expired by the time you get to the view:
Controller
public ActionResult ViewRedirect()
{
ViewData["Content"] = "some text";
return RedirectToAction("ViewTest");
}
public ActionResult ViewTest()
{
return View(); // ViewData["Content"] expires
}
View
<div>
ViewData content: @ViewData["Content"]
</div>
Result
<div>
ViewData content:
</div>
References