In ASP.Net MVC, we can pass data from the controller to the corresponding view using ViewData and ViewBag. We can also pass data from the View to Controller using Post/ QueryString/ HiddenField and Controller to Controller using TempData.
In this post, we will learn how to pass data from Controller to View in ASP.NET MVC using ViewData and ViewBag. In the previous ASP.NET MVC tutorials, we saw:
ViewData
ViewData is a dictionary object used to pass data from the controller to view in the form of Key-Value pair. ViewData is derivative of the ViewDataDictionary class. ViewData is introduced in MVC 1.0. ViewData requires type casting for complex data types and if redirection occurs, itS value becomes NULL.
Example of ViewData:
Create a new empty ASP.NET MVC Project and Add a Controller named
HomeController.
Store the current DateTime in ViewData object and return a View. Now add a View (named
Index).
- public ActionResult Index()
- {
- ViewData["DateTime"] = DateTime.Now;
- return View();
- }
Now call the ViewData["DateTime"] object in View using @ symbol because we have selected the Razor View Engine.
Index.cshtml Code
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>ViewData Example</h2>
- <p>@ViewData["DateTime"]</p>
Preview
ViewBag
ViewBag is a dynamic property (a new C# 4.0 feature) which means it has no pre-defined properties. ViewBag is a wrapper around the ViewData that exposes the ViewData dictionary as a dynamic object. ViewBag is slower than ViewData and it does not require any type of typecasting for the complex data type. Visual Studio cannot provide IntelliSense support for the dynamic objects, so error is not visible at the design time.
Example of ViewBag:
Inside HomeController, Add another Action Method (named it Demo). Store the current DateTime in ViewBag.DateTime dynamic object and return a View.
- public ActionResult Demo()
- {
- ViewBag.DateTime = DateTime.Now;
- return View();
- }
Now add a View (named Demo).
Demo.cshtml Code
- @{
- ViewBag.Title = "Demo";
- }
-
- <h2>ViewBag Demo</h2>
- <p>@ViewBag.DateTime</p>
Preview:
Hope you liked it. Thanks!