Passing Data From Controller To View In ASP.NET MVC

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).
  1. public ActionResult Index()  
  2. {  
  3.     ViewData["DateTime"] = DateTime.Now;  
  4.     return View();  
  5. }  
 

Now call the ViewData["DateTime"] object in View using @ symbol because we have selected the Razor View Engine.

Index.cshtml Code
  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <h2>ViewData Example</h2>  
  6. <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.
  1. public ActionResult Demo()  
  2. {  
  3.    ViewBag.DateTime = DateTime.Now;  
  4.    return View();  
  5. }  
Now add a View (named Demo).

 

Demo.cshtml Code
  1. @{  
  2.     ViewBag.Title = "Demo";  
  3. }  
  4.   
  5. <h2>ViewBag Demo</h2>  
  6. <p>@ViewBag.DateTime</p>  
Preview:

 

Hope you liked it. Thanks!

Up Next
    Ebook Download
    View all
    Learn
    View all