About Article
This article will tell you almost everything you need to know about passing the data from Controller to View in ASP.NET MVC using ViewBag.
I am writing this article to tell you the basic to advanced foremost concepts about ways to pass data from Controller to View. This article is the third one in the series named “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.
- Passing Data From Controller To View With ViewData - Part Two
- 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
The topics to be covered are,
- Drawbacks of ViewData
- What is ViewBag?
- Passing the data from Controller to View using ViewBag
- What happened if ViewData and ViewBag call the same Key’s value?
As we know, Controller is the class that is responsible to handle all the HTTP requests and then to execute the 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 the next articles, you will learn how to pass data from Controller to View.
In this article, you’ll learn how to pass a strongly-typed data from Controller to View using ViewBag. And, you’ll see other ways to pass the data, in coming articles. So, stay tuned!
ViewData and its Drawbacks
As you have seen in my previous article, ViewData is the dictionary containing Key-Value pair in which the Key must be a string. ViewData is the property of ControllerBase class and can be accessible in every Controller. ViewData is used to pass the data from the Controller to the corresponding View, importantly its redirection can’t be possible. ViewData is must be cast before use in the View. Let’s move towards its code to see its drawbacks.
For Controller, code of passing data (the employee object) using ViewData is as follows,
- ViewData["EmployeeData"] = emp;
- @foreach (var employee in (IEnumerable<Employee>)ViewData["EmployeeData"])
- {
- <tr>
- <td>@employee.EmployeeId</td>
- <td>@employee.EmployeeName</td>
- <td>@employee.Address</td>
- <td>@employee.Phone</td>
- </tr>
- }
- @(((Employee)ViewData["EmployeeData "]). EmployeeName)
- ViewData["EmployeeData"]
What is ViewBag?
ViewBag is a dynamic property and a wrapper around the ViewData. It is a dynamic object and any number of field can be added into it dynamically. We can pass both strongly and weekly typed data using ViewBag. It doesn’t require any typecasting for complex and strongly typed data.
ViewBag is also one of the properties of “ControllerBase” class so when we create a controller, that controller will automatically inherit the “Controller” abstract class and this “Controller” class inherits “ControllerBase” abstract class, that’s why we can access this ViewBag property in each controller. You can see in the image below the “Controller” class which inherits the “ControllerBase” class.
- 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 the dynamic view data dictionary.</summary>
- /// <returns>The dynamic view data dictionary.</returns>
- public dynamic ViewBag { get; }
- }
- }
Passing the data from Controller to View using ViewBag
To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property. 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
- {
- [Display(Name = "Serial No")]
- public byte EmployeeId { get; set; }
- [Display(Name = "Name")]
- 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"
- }
- };
- ViewBag.employee = emp;
- return View();
- }
- }
- @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 ViewBag.employee)
- {
- <tr>
- <td>@employee.EmployeeId</td>
- <td>@employee.EmployeeName</td>
- <td>@employee.Address</td>
- <td>@employee.Phone</td>
- </tr>
- }
- </tbody>
- </table>
To iterate the data, here we have used ViewBag which is calling the data from Controller with the help of property named as “employee”. And you can also see that we don’t have to cast the ViewBag to Employee. Now simply build and run the application then you’ll see the following output,
It will print the same output for both ViewBag and ViewData. It’ll not throw any exception or error. Now let’s understand its concept. As we know, ViewBag is a wrapper around ViewData as shown below,
In the “GetEmployeeData” action method of “EmployeeDataController”, I write the following code in which I use both ViewData and ViewBag with the same Key and Property name “exm” respectively.
- ViewData["exm"] = "Shah";
- ViewBag.exm = "Zain";
- <br/>
- <strong>Output:</strong>
- <br/>
- <text>We use both ViewBag and ViewData then the output will be as follows:</text>
- <br/>
- @ViewBag.exm
- <br/>
- @ViewData["exm"]
The reason for such Output
As we know the ViewBag is a wrapper around ViewData and both stores its data into Dictionary. The dictionary contains a Key-Value pair where the Key must be a string. When ViewData["exm"] = "Shah"; executes, it creates result in the dictionary having Key as “exm” and Value as “Shah”. You can see below in the image when I put a breakpoint on ViewData.
As in the dictionary, there is one key named as “exm” and one value named as “Zain”. Then, both ViewData and ViewBag will print the same output as given below.
In this article, you have learned how to pass strongly typed data from Controller to View using ViewBag, in which firstly, you should make a model class then populate its properties with some data then pass that object to the ViewBag as Value and pass magic property (Key) as a string. You have learned that what happened if the magic property of ViewBag and magic key of ViewData becomes same 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 ViewBag in ASP.NET MVC. Stay tuned for my next articles because this article is the third 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