Updated April 3, 2023
Introduction to ViewBag in MVC
In an MVC application, it is a very common thing that we feel the necessity of passing the values and data from the controller to view part of the code. In these situations, if we are using ASP.Net MVC then we can achieve our goal using four types of possibilities. We can pass the data from the action method of the controller to the view by using either ViewData, ViewBag, TempData, or a strongly typed model. ViewData and ViewBag are similar in working having some differentiation when it comes to handling and using them. They both provide the same functionality to pass data from controller to view but ViewData needs typecasting which is not the case while using ViewBags. Dynamism is the advantage of ViewBag. In this article why and how we can use ViewBags in MVC architecture.
ViewBag is a wrapper around ViewData that uses the dynamic functionality of C# 4.0 and is itself a dynamic property. When ViewBag is used, we don’t need to worry about typecasting while retrieving the values in view if ViewBag is used to send data from the controller’s action method to view part of the code. The ViewBag remains in function only for the current request and gets destroys on redirection of the flow of code.
Syntax:
Below is the syntax:
[Dynamic]
public dynamic ViewBag { get; }
As can be seen from its signature, it returns the dynamic object which can store any format of the data in it. This is the reason why we don’t need typecasting while using it for data transfer from the controller to view. Let us now see how we can use it with different data types in the controller while passing and viewing while retrieving with the help of an example.
1. ViewBag in ASP.NET MVC with String Type:
Storing Data in ViewBag
ViewBag.HeaderString = "EDUCBA - Platform For Learning";
Retrieving Data from ViewBag
@ViewBag. HeaderString
2. ViewBag in ASP.NET MVC with Complex Type:
Storing Data in ViewBag
ViewBag.Details = details;
Retrieving Data from ViewBag
@{
var details = ViewBag.Details
}
As can be seen from the above snippets of code, no typecasting is required while collecting string or any complex data in the view. Similar is the case with other data types. Now, let’s look at the example and full code.
Examples to Implement ViewBag in MVC
Now we will have an example where we will be storing the platform details for learning technologies and then will return the details to the view as demonstrated in the above abstraction. The header string will be assigned in the controller and will build a separate entity or model for the details object which we want to pass who’s values will be collected from another business layer or service part of the code where we will write the method to assign and return the object of details along with its specified values. We will firstly begin by writing the code for the model details. We will be storing PlatformId, Name, EstablishDate, Technologies, TeamSize, HeadQuarter, Address and ContactNo of the platform and display all the details in the view section.
1. Details Model
Code:
public class Details
{
public int PlatformId { get; set; }
public string Name { get; set; }
public string EstablishDate { get; set; }
public string Technologies { get; set; }
public int TeamSize { get; set; }
public string HeadQuarter { get; set; }
public string Address { get; set; }
public int ContactNo { get; set; }
}
Now, we will code for the method which will get the details object and return it to the controller. For now, we will add the static data to the properties of the Details Object and return that object from the GetPlatformDetails method. Here’s the code for the service or business layer file named PlatformBusinessLayer which will consist of our method.
2. Service Layer File
Code:
public class PlatformBusinessLayer
{
public Details GetPlatformDetails(int PlatformId){
Details demo=new Details()
{
demo.PlatformId = 1 ,
demo.Name = "EDUCBA" ,
demo.EstablishDate = "XX/YY/ZZZZ" ,
demo.Technologies = "Javascript, ASP.Net MVC, Maven, Hibernate and many more" ,
demo.TeamSize = 1000 ,
demo.HeadQuarter = "Mumbai" ,
demo.Address = "A- 406, Boomerang, Chandivali Rd, Powai, Mumbai, Maharashtra 400072" ,
demo.ContactNo = 1234567890
};
return demo;
}
}
So now we are ready to go for the crux of the code that is our controller file. Here, we will create the object of service file and get the detailed object value from the method, assign header string object value and return both these properties with the help of ViewBag to the view section of the code.
3. Controller File
Code:
using FirstMVCDemo.Models;
using System.Web.Mvc;
namespace FirstMVCDemo.Controllers
{
public class MyDemoController : Controller
{
public ActionResult Index()
{
PlatformBusinessLayer PlatformServiceObj = new PlatformBusinessLayer();
Details details = PlatformServiceObj.GetPlatformDetails(1);
ViewBag.Details = details;
ViewBag.HeaderString = "EDUCBA Details";
return View();
}
}
}
Finally, now we will retrieve the values stored in our ViewBag Object in the view part of our code. In the GUI of our sample demo, we will retrieve the header string and display it in the header section. Further, we will create a variable to store the details object and will retrieve each property of it and display it in the tabular format.
4. View File
Code:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Sample ASP.Net ViewBag Demonstration</title>
</head>
<body>
@{
var details = ViewBag.Details;
}
<h2>@ViewBag.HeaderString</h2>
<table style="font-family:Arial">
<tr>
<td>Platform ID:</td>
<td>@details.PlatformId </td>
</tr>
<tr>
<td>Name:</td>
<td>@details.Name</td>
</tr>
<tr>
<td>EstablishDate:</td>
<td>@details.EstablishDate</td>
</tr>
<tr>
<td>Technologies:</td>
<td>@details.Technologies</td>
</tr>
<tr>
<td>TeamSize:</td>
<td>@details.TeamSize</td>
</tr>
<tr>
<td>HeadQuarter:</td>
<td>@details.HeadQuarter</td>
</tr>
<tr>
<td>Address:</td>
<td>@details.Address</td>
</tr>
<tr>
<td>ContactNo:</td>
<td>@details.ContactNo</td>
</tr>
</table>
</body>
</html>
Here. We are accessing the dynamic properties of the ViewBag which are HeaderString and Details respectively and displaying in the tabular format. Now we are ready to run our code on the “/Home/Index” URL. Then our expected output will be displayed which is as follows –
The final code which is rendered by the browser is somewhat as shown below –
5. Browser Rendered Code
Code:
<!DOCTYPE html>
<html>
<body>
<h2>Sample ASP.Net ViewBag Demonstration</h2>
<h2>EDUCBA Details</h2>
<table style="font-family:Arial">
<tr>
<td>Platform ID:</td>
<td>1 </td>
</tr>
<tr>
<td>Name:</td>
<td>EDUCBA</td>
</tr>
<tr>
<td>EstablishDate:</td>
<td>XX/YY/ZZZZ</td>
</tr>
<tr>
<td>Technologies:</td>
<td>Javascript, ASP.Net MVC, Maven, Hibernate and many more</td>
</tr>
<tr>
<td>TeamSize:</td>
<td>1000</td>
</tr>
<tr>
<td>HeadQuarter:</td>
<td>Mumbai</td>
</tr>
<tr>
<td>Address:</td>
<td>A- 406, Boomerang, Chandivali Rd, Powai, Mumbai, Maharashtra 400072</td>
</tr>
<tr>
<td>ContactNo:</td>
<td>1234567890</td>
</tr>
</table>
</body>
</html>
The ViewBag is the Dynamic property that is detected and rendered during run-time. So even if you have any spelling mistakes or other such errors in your code, you won’t be told about it during compile-time. You will only get to know about this after you run your code and check the working. This is also the reason why intelligence support can’t be provided while coding with ViewBags.The same is the case while using ViewData. As ViewBag is the wrapper of ViewData, if the same-named property is used in both it will throw a run-time exception if the key of ViewData is the same as the property of ViewBag.
Conclusion
It is important to note the difference and similarities in ViewData and ViewBag usage. ViewData is the dictionary object which uses a string as the key to store the object data while ViewBag is the dynamic property that uses dynamic properties to store and return the data of the object. Both are used for returning the data from the controller’s action methods to the view for further rendering and give run-time errors and exceptions if any mistake is there in coding. Typecasting of the passed objects needs to be done in the view section of the code when ViewData is used.ViewBag doesn’t need the typecasting of the objects. Both of the methods do not support compile-time error support and intelligence and hence are not much preferred while sending the data from the controller to the view. However, if necessary always prefer ViewBag over ViewData. The best way to transfer data from controller to view is by using strongly-typed models as they provide compile-time error checking and intelligence support.
Recommended Articles
We hope that this EDUCBA information on “ViewBag in MVC” was beneficial to you. You can view EDUCBA’s recommended articles for more information.