Updated March 30, 2023
Introduction to ASP.NET MVC ViewBag
ASP.NET MVC framework provides us an option to pass the data from controller to view. ViewBag is actually a wrapper around view data. With ViewBag we use dynamic properties. It is useful when we want to send a temporary small amount of data to view from the controller. It is a dynamic type property of the ControllerBase class. This class is a base class of all other controllers. ViewBag only transfers data from controller to view but vice versa is not possible. If vice versa happens then the value will be null for ViewBag.
In the above snippet, you can see the name property is attached to the ViewBag with the notation dot and it assigns a string “EduCba” to it in the controller. So this will be accessed in the view like @ViewBag.Name. We know @ is a razor symbol or syntax which is used to access the server-side variable.
When it will be used?
It is basically used when we want to allow to share dynamic values. There are many variables whose values are entered during runtime only. These variables are not known before we run the program. So this is the major reason why is it used as we can put any value in ViewBag. In addition, we can also use ViewBag Objects for less amount of data which we will transfer from the controller to view. There are so many cases where it will work well like Drop down list options, shopping carts, widgets, and aggregated data.
Syntax For ViewBag:
With String Type
ViewBag in asp.net with complex type
Examples of ASP.NET MVC ViewBag
Given below are the examples:
Example #1
Let us take an example of ViewBag. Suppose we have a list of subjects that is Math, Hindi, English, Science, and History to display.
Here we are creating a controller first and then it will return a view to the browser. The controller will pass Subject ViewData to the View.
First, we need to create a new MVC application in the home Controller and then write the following code.
Code:
using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace ViewBagExample.Controllers
{
public class ViewBagController : Controller
{
// GET: ViewBag
public ActionResult Index()
{
List<string> Subject = new List<string>();
Subject.Add("Math");
Subject.Add("Hindi");
Subject.Add("English");
Subject.Add("Science");
Subject.Add("History");
ViewData["Subject"] = Subject;
return View();
}
}
}
View
// Index.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h2>List of Subject</h2>
<ul>
@{
foreach (var Subject in ViewData["Subject"] as List<string>)
{
<li> @Subject</li>
}
}
</ul>
</body>
</html>
This will give output with the list of subjects mentioned in the controller that means it will pass the values of the controller to view.
Output:
In the below output we can see the List of subjects are displayed
Example #2
Let us take one smaller example by taking the date and time. As usual, we need to create MVC application in-home controller and write the following code in the index method.
Code:
{
Public ViewResult Index()
{
ViewBag.Message="Good Morning";
ViewBag.Date=DateTime.Now;
Return View();
}
We have defined two properties Message and Date by assigning values to them. The message contains “Good Morning” value and the Date contains “DateTime.Now” which will pass the current time.
Now if we want to read the data, we need to get the same properties that we set in the action methods.
We need to write the below code in Index.cshtml.
Code:
@{
ViewBag.Title="Index";
}
<h2>Index</h2>
Greeting from us:@ViewBag.Message
Today date is @ViewBag.Date
Output:
Below is the output for the code, it will give us the ViewBag message, which is passed, and today’s date.
Some Points Regarding ViewBag
- ViewBag is a wrapper around viewdata.
- We can assign n number of properties to the ViewBag and provide values to it.
- It is very easy to use as this is implemented as a property of both the view as well as the controller.
- ViewBag is mandatory when we are specifying a title page on any given view.
- We can assign the same property name multiple times to viewBag.
- It will consider the last value assigned to the property even if multiple property names are given.
- It cannot pass the data back to the controller.
- It is simpler to check for the null values.
- Syntax of ViewBag makes it easier and faster to add a controller and views.
- As ViewBag is DynamicViewData object it will provide dynamic access to the objects which are stored in the ViewData.
- ViewBag does not require any casting so that is why it is more convenient and easy to use.
- The syntax of ViewBag makes it quicker to add to controllers and views.
Limitations
- It is basically used to transfer the small amount of data to the controller. The statement itself tells us the limitation that it is not suitable for the larger amount of data or more complex ones.
- Data like complex relational Data, big sets of aggregate data, dashboard data or the data, which is coming from the different sources. In addition, there is some potential problem when we use it.
- During compilation things, errors are not easily detected for instances. Dynamic nature allows it to create ViewBag names accordingly; however, these are not checked during compilation as other types do. This means we will not be able to detect if we used the right names and if it matches the view where the name is specified. In addition, ViewBag is not available in Razor Pages.
Conclusion – ASP.NET MVC ViewBag
We can conclude that ViewBag is just a wrapper round ViewData. It is a dynamic property, which uses new dynamic properties in C# 4.0. Also, we can assign any number of properties as well as pass values to ViewBag. It lasts only until the current request of http.in. In addition, it is useful for a small number of data sets.
Recommended Articles
We hope that this EDUCBA information on “ASP.NET MVC ViewBag” was beneficial to you. You can view EDUCBA’s recommended articles for more information.