About Article
This article will tell you almost everything about passing data from Controller to View in ASP.NET MVC using ViewData.
I am writing this article to tell you the basic to advance foremost concepts about ways to pass data from Controller to View. This article is the second one in the series named as “Passing Data from Controller to View”. You’ll learn all the ways in each separate article. Stay tuned!
I would strongly recommend reading my previous articles, which will be defining the basic concepts ASP.NET MVC. Articles are listed below:
- Passing Data From Controller To View - Part One
- Action Selectors In ASP.NET MVC
- Filters In ASP.NET MVC
- Action Result In ASP.NET MVC
- MVC Architecture And Its Pipeline
- Convention Routing VS Attribute Routing
Read this article, check the code after downloading, and then feel free to give your feedback.
The topics to be covered are,
- What is ViewData?
- Passing the data from Controller to View using ViewData
As we know Controller is the class whose responsibility is to handle all the HTTP requests and then execute appropriate View. And View gives us the HTML markup that we display to the user. And for displaying anything on the View, there should be some data that is passed from Controller to View. And in this and next articles, you will learn how to pass data from Controller to View.
In this article, you’ll learn how to pass strongly typed data from Controller to View using ViewData. And you’ll see other ways to pass data, in coming articles. So stay tuned.
What is ViewData?
ViewData is a dictionary for the view data having the type of ViewDataDictionary. And it is one of the properties of ControllerBase class so when we create a Controller, then that Controller will automatically inherit the Controller class and this Controller class inherits ControllerBase class. That’s why we can be able to access this ViewData property in each Controller. You can see in the image below the Controller class which inherits the ControllerBase class.
And in the ControllerBase class, the ViewData property is defined, see below its syntax.
- namespace System.Web.Mvc
- {
- /// <summary>Represents the base class for all MVC controllers.</summary>
- public abstract class ControllerBase : IController
- {
- //Other code is removed for clarity.
- /// <summary>Gets or sets the dictionary for view data.</summary>
- /// <returns>The dictionary for the view data.</returns>
- public ViewDataDictionary ViewData { get; set; }
- }
- }
Passing the strongly typed data from Controller to View using ViewData
To pass the strongly-typed data from Controller to View using ViewData, we have to make a model class then populate its properties with some data and then pass that data to ViewData dictionary as Value and selecting Key’s name is the programmer’s choice. And then in the View, we can access the data of model class by using ViewData dictionary with the pre-defined keys. Let’s create a project to take a look at an example.
Go to File then New and select “Project” option.
Now, create a class named as “Employee” in the Models folder, shown below.
- namespace DataCtoV.Models
- {
- public class Employee
- {
- public byte EmployeeId { get; set; }
- public string EmployeeName { get; set; }
- public string Address { get; set; }
- public string Phone { get; set; }
- }
- }
- public class EmployeeDataController : Controller
- {
- // GET: EmployeeData
- public ActionResult GetEmployeeData()
- {
- List<Employee> emp = new List<Employee>
- {
- new Employee
- {
- EmployeeId = 1,
- EmployeeName = "John",
- Address = "12 Fremont St. Clermont, FL 2813",
- Phone = "+1-234-2838421"
- },
- new Employee
- {
- EmployeeId = 2,
- EmployeeName = "Smith",
- Address = "14 Highland Drive Fort Worth, TX 3994",
- Phone = "+1-234-2244521"
- },
- new Employee
- {
- EmployeeId = 3,
- EmployeeName = "Marry",
- Address = "23 Fremont Road Milledgeville, GA 6788",
- Phone = "+1-234-46568421"
- }
- };
- ViewData["EmployeeData"] = emp;
- return View();
- }
- }
- @using DataCtoV.Models
- @model IEnumerable<DataCtoV.Models.Employee>
- @{
- ViewBag.Title = "Employee Data";
- }
- <h3>Employee Data</h3>
- <table class="table table-condensed table-hover">
- <thead>
- <tr>
- <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>
- <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>
- <th>@Html.DisplayNameFor(e => e.Address)</th>
- <th>@Html.DisplayNameFor(e => e.Phone)</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var employee in (IEnumerable<Employee>)ViewData["EmployeeData"])
- {
- <tr>
- <td>@employee.EmployeeName</td>
- <td>@employee.EmployeeName</td>
- <td>@employee.Address</td>
- <td>@employee.Phone</td>
- </tr>
- }
- </tbody>
- </table>
To iterate the data, here, we have used ViewData dictionary which is calling the data from Controller with the help of Key named as “EmployeeData”. And you can also see that we have cast the ViewData to Employee.
NoteWe must have to cast the ViewData before using it.
Why casting?
To iterate the data of Employee’s collection properly, we have to cast it to IEnumerable, because there a list/collection of Employees is coming and only in IEnumerable, the GetEnumerator is defined for iterating it properly. Hence we must have to cast it in the foreach loop. See the Error below without casting.
One way of casting the ViewData is described above, which is at a time casting of ViewData in the foreach loop. The code is given below.
Casting in the code block,
- @{
- ViewBag.Title = "Employee Data";
- var employeeData = (IEnumerable<Employee>)ViewData["EmployeeData"];
- }
- @foreach (var employee in employeeData)
- {
- <tr>
- <td>@employee.EmployeeName</td>
- <td>@employee.EmployeeName</td>
- <td>@employee.Address</td>
- <td>@employee.Phone</td>
- </tr>
- }
GetEmployeeData.cshtml
- @using DataCtoV.Models
- @model IEnumerable<DataCtoV.Models.Employee>
- @{
- ViewBag.Title = "Employee Data";
- var employeeData = (IEnumerable<Employee>)ViewData["EmployeeData"];
- }
- <h3>Employee Data</h3>
- <table class="table table-condensed table-hover">
- <thead>
- <tr>
- <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>
- <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>
- <th>@Html.DisplayNameFor(e => e.Address)</th>
- <th>@Html.DisplayNameFor(e => e.Phone)</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var employee in employeeData)
- {
- <tr>
- <td>@employee.EmployeeId</td>
- <td>@employee.EmployeeName</td>
- <td>@employee.Address</td>
- <td>@employee.Phone</td>
- </tr>
- }
- </tbody>
- </table>
To change this name we have to apply a data annotation to EmployeeId and EmployeeName property, named as Display and then set its Name property to “Serial No” and “Name” respectively. You can see the changed code of “Employee” model class below,
- [Display(Name = "Serial No")]
- public byte EmployeeId { get; set; }
- [Display(Name = "Name")]
- public string EmployeeName { get; set; }
In this article, you have learned that how to pass strongly typed data from Controller to View using ViewData dictionary, in which firstly, you should make a model class then populate its properties with some data then pass that object to the ViewData dictionary as Value and pass Key as a string. You have learned it with the help of an example.
Conclusion
I hope this article has helped you in understanding the concepts about passing strongly typed data from Controller to View using ViewData in ASP.NET MVC. Stay tuned for my next articles because this article is the second one in the series of “Passing data from Controller to View” and you’ll learn more about passing data in coming articles. If you have any query, please feel free to contact me in the comments section. Also, do provide the feedback whether positive or negative. It will help me to make my articles better and increase my enthusiasm to share my knowledge.
No comments:
Post a Comment