ASP.NET MVC

Various Methods of Data Transmission from Controllers to Views | ASP.NET MVC

Various Methods of Data Transmission from Controllers to Views | ASP.NET MVC

Various Methods of Data Transmission from Controllers to Views

There are several techniques to transfer data or value from the controller to the view.

ViewData Dictionary Property
By adding objects to the ViewData dictionary using a key/value pattern, you can supply data that you want to give to a view.

//Controller
ViewData["username"] = "Mc";

<!-- View -->
<pre>@ViewData["username"]</pre>



ViewBag Property
In ASP.NET MVC, temporary data (that isn't part of the model) is transferred from the controller to the view via the ViewBag.
It is a dynamic type property of the ControllerBase class, which serves as the Controller class's base class, on the inside.

//Controller
ViewBag.TotalEmployees = employeeList.Count();

<!-- View -->
<label>Total Employees:</label>  @ViewBag.TotalEmployees



ViewData
Used to pass data from controller to view.
  • It is derived from ViewDataDictionary class.
  • It is available for the current request only.
  • Requires typecasting for complex data types and checks for null values to avoid an error.
  • If redirection occurs, then its value becomes null.

     
ViewBag
Used to pass data from the controller to the respective view, using a dynamic property. 
  • It is also available for the current request only.
  • If redirection occurs, then its value becomes null.
  • It doesn’t require typecasting for the complex data type.
     
 
TempData
Helps to maintain the data when we move from one controller to another controller or from one action to another action. TempData, Derived from TempDataDictionary class, and is used to pass data from the current request to the next request
  • Keeps its information for the time of an HTTP Request i.e. request from one page to another. 
  • Requires typecasting for complex data types and checks for null values to avoid an error. 
  • In General, it is used to store only one time messages like the error messages and validation messages



Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram