In this article I will explain a short tutorial with example on how to use ViewData in ASP.Net MVC.
ViewData is derived from the ViewDataDictionary class and is basically a Dictionary object used for passing data from Controller to View.
 
 
What is ViewData
1. ViewData is derived from the ViewDataDictionary class and is basically a Dictionary object i.e. Keys and Values where Keys are String while Values will be objects.
2. Data is stored as Object in ViewData.
3. While retrieving, the data it needs to be Type Casted to its original type as the data is stored as objects and it also requires NULL checks while retrieving.
4. ViewData is used for passing value from Controller to View.
5. ViewData is available only for Current Request. It will be destroyed on redirection.
 
 
Example
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, a string value is set in the ViewData object in Controller and it is then displayed in View.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        ViewData["Message"] = "Hello MVC!";
        return View();
    }
}
 
View
Inside the View, simply the ViewData object is used to display the Message.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @ViewData["Message"]
    </div>
</body>
</html>
 
 
Screenshot
ASP.Net MVC: ViewData Tutorial with example
 
 
Downloads