ViewData is a dictionary which holds the objects derived from ViewDataDictionary class. ViewData is one of the way to pass data from the controller to view.
Description
View data value becomes null when the redirection occurs. That means ViewData has a short life. View Data is also used to maintain some data that means view data is used like state management technique in ASP.Net.
ViewData is almost similar to TempData. ViewData Variable can be used only once in one Application.When gone for the next request, then the ViewData Variables are destroyed automatically.
If wanted to give multiple requests. Then the ViewData is not useful.
In general, Viewdata Variables are maintained by the View Context Object.
ViewData Variable can be accessed from the view in three ways
ViewData[“KeyName”]
ViewContext.ViewData[“KeyName”]
ViewContext.Controller.ViewData[“KeyName”]
Examples
The below steps explain view data.
Step 1
Open the Visual studio 2013(whatever the version you have). Create an MVC Application. Add the controller and give the name as HomeController. Now, add view and give the name as the ViewDataExample.
Note
If having any doubts while adding view or controller, please refer the previous chapters.
Step 2
Write the following code under the HomeController.cs.
[csharp]
public ActionResult ViewDataExample()
{
ViewData["a"] = 10;
ViewData["b"] = 45.5;
ViewData["s"] = "James";
return View();
}
[HttpPost]
public ActionResult ViewDataExample(string x)
{
ViewData["X"]="Welcome to SPlessons Tutorials"
return View();
}
[/csharp]
Step 3
Write the following code under theViewDataExample.cshtml.
[html]
@{
ViewBag.Title = "ViewDataExample";
}
<h2>TempDataExample</h2>
<form name="f1" method="post">
<div>
Value of a is :@ViewData["a"]
Value of b is :@ViewContext.ViewData["b"]
Value of s is :@ViewContext.Controller.ViewData["s"]
Value of X is :@ViewData["X"]
<input type="submit" value="SUBMIT" name="B1" />
</div>
</form>
[/html]
Step 4
Change the Action name as ViewDataExample in Routeconfig.cs.
Note
If you have any doubts regarding RoutecConfig.cs, please refer the previous chapters.
Step 5
press f5 to run the application. The following output will appear.
Step 6
Click on the Submit button. Then the following window will appear.
Step 7
Observe the difference between two outputs. For the second request viewdata variables are destroyed.