ViewBag, ViewData, and TempData all are Dictionary objects in ASP.NET MVC and these are used for data passing in various situations.
The following are the situations where we can use TempData and other objects.
- Pass the data from Controller to View.
- Pass the data from an action to another action in Controller.
- Pass the data in between Controllers.
- Pass the data between consecutive requests.
What is Dictionary Object?
In C#, Dictionary is used to store the key-value pairs. The Dictionary is the same as the non-generic hashtable. It can be defined under System.Collection.Generic namespace. It has a dynamic nature which means the size of the dictionary grows according to the need.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | using System; using System.Collections.Generic; class Demo { static public void Main () { Dictionary<int, string> My_dict1 = new Dictionary<int, string>(); My_dict1.Add(1123, "Welcome"); My_dict1.Add(1124, "to"); My_dict1.Add(1125, "Programming"); foreach(KeyValuePair<int, string> ele1 in My_dict1) { Console.WriteLine("{0} and {1}", ele1.Key, ele1.Value); } Console.WriteLine(); Dictionary<string, string> My_dict2 = new Dictionary<string, string>(){ {"a.1", "Dog"}, {"a.2", "Cat"}, {"a.3", "Pig"} }; foreach(KeyValuePair<string, string> ele2 in My_dict2) { Console.WriteLine("{0} and {1}", ele2.Key, ele2.Value); } } } |
What is ViewData?
In MVC, when we want to transfer the data from the controller to view, we use ViewData. It is a dictionary type that stores the data internally.
ViewData contains key-value pairs which means each key must be a string in a dictionary.
The only limitation of ViewData is, it can transfer data from controller to view. It can not transfer in any other way and it is valid only during the current request.
Syntax:
| public ViewDataDictionary ViewData { get; set; } |
When we want to use the key-value pair to ViewData,
| ViewData["DemoText”]="This is syntax."; |
We can also use ViewData in the razor view from controller. Here is the syntax for that:
| <h1>@ViewData["PageTtitle"]</h1> |
When we want to add custom objects, array, list, etc, in ViewData, and cast them back in the View. We can use the code snippet as below:
| public ActionResult actionViewData() { ArrayList alCit y = new ArrayList(); alCity.Add("Ahmedabad"); alCity.Add("Rajkot"); alCity.Add("Amreli"); alCity.Add("Bhavnagar"); alCity.Add("Surat"); alCity.Add("Junagadh"); alCity.Add("Vadodara"); ViewData["City"] = alCity; return View(); } |
| @{ ArrayList _city = ViewData["City"] as ArrayList; foreach (string city in _city) { <div>@city</div> } } |
Figure 1: ViewData Flow
Here is an example of ViewData which shows how to transfer data from controller to view using ViewData.
| public ActionResult Index() { IList<Employee> employeeList = new List<Employee>(); employeeList.Add(new Employee(){ EmployeeName = "Hemanshu" }); employeeList.Add(new Employee(){ EmployeeName = "Harsh" }); employeeList.Add(new Employee(){ EmployeeName = "Hiren" }); ViewData["employees"] = employeeList; return View(); } |
In this example, ViewData[“employees”] is assigned to an employeeList where “employees” is a key and employeeList is a value.
To access the ViewData[“employees”] in the view, here is the snippet of code you can use.
| <ul> @foreach (var std in ViewData["employees"] as IList<Employee>) { <li> @emp.EmployeeName </li> } </ul> |
In simple terms, these are the ways to store and retrieve data to and for respectively ViewData as shown:
Storing :
| ViewData[“employees”] = employeeList; |
Retriving :
| string employee = ViewData[“Employee”].ToString(); |
In MVC, ViewData does not check compile-time errors. If we misspell the key names, we would not get any errors but we can identify them at the run time.
For example,
Controller:
| using System.Collections.Generic; using System.Web.Mvc; namespace DemoMvcApplication.Controllers{ public class HomeController : Controller{ public ViewResult Index(){ ViewData["Countries"] = new List<string>{ "India", "Malaysia", "Dubai", "USA", "UK" }; return View(); } } } |
View
| @{ ViewBag.Title = "Countries List"; } <h2>Countries List</h2> <ul> @foreach(string country in (List<string>)ViewData["Countries"]){ <li>@country</li> } </ul> |
Figure 2: Output
What is ViewBag?
ViewBag is an object which is dynamically passing the data from Controller to View and this will pass the data as the property of object ViewBag. We do not need to typecast to read the data for null checking here.
Controller:
| Public ActionResult Index() { ViewBag.Title = “Hello”; return View(); } |
View:
| <h2>@ViewBag.Title</h2> |
Here is an example:
Controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System; using System.Collections.Generic; using System.Web.Mvc; namespace ViewBagExample.Controllers { public class ViewBagController : Controller { public ActionResult Index() { List<string> Courses = new List<string>(); Courses.Add("J2SE"); Courses.Add("J2EE"); Courses.Add("Spring"); Courses.Add("Hibernates"); ViewBag.Courses = Courses; return View(); } } } |
View:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <h2>List of Courses</h2> <ul> @{ foreach (var Courses in ViewBag.Courses) { <li> @Courses</li> } } </ul> </body> </html> |
Figure 3: Output
What is TempData?
TempData is a dictionary object derived from TempDataDictionary which contains key-pair values. It is useful when we want to transfer the data from the Controller to the View in ASP.NET MVC Application. It stays for a subsequent HTTP request as opposed to other options we discussed prior who stay only for the current request.
Although it removes the key-value pair once it is accessed, we can keep it using
Here is an example:
Controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class HomeController : Controller { public ActionResult Index() { TempData["name"] = "Ishan"; return View(); } public ActionResult About() { string name; if(TempData.ContainsKey("name")) name = TempData["name"].ToString(); return View(); } public ActionResult Contact() { return View(); } } |
View:
| public class HomeController : Controller { public ActionResult Index() { TempData["name"] = "Ishan"; return View(); } public ActionResult About() { return View(); } public ActionResult Contact() { return View(); } } |
Differences between ViewData, ViewBag and TempData:
ViewData | ViewBag | TempData |
Key-Value Dictionary Object | Type Object | Key-Value Dictionary Collection |
A property of ControllerBase class | A Dynamic property of ControllerBase class | A property of the controllerBase class |
Faster | Slower | – |
Introduced in MVC 1.0, Available in MVC 1.0 and above | Introduced in MVC 3.0, Available in MVC 3.0 and above | Introduced in MVC 1.0, Available in MVC 1.0 and above. |
Works with .NET Framework 3.5 and above | Works with .NET framework 4.0 and above | Works with .NET framework 3.5 and above |
Type Conversion code is required | Type Conversion code is not required | Type Conversion code is required |
Value becomes null if a redirection has occurred | Value becomes null if a redirection has occurred | TempData is used to pass data between two consecutive requests |
Lies only during the current request | Lies only during the current request | Only works during the current and subsequent request |
Conclusion
Figure 4: Summary
To conclude, it is clear that ViewData is used to pass the data from Controller action to View. Here, we discussed ViewData properties and how to use that in any MVC application.
Source : https://www.red-gate.com/simple-talk/blogs/what-is-viewdata-and-implement-viewdata-in-asp-net-mvc/