Stackify is now BMC. Read theBlog

ViewBag 101: How It Works, When It’s Used, Code Examples, and More

By: HitSubscribe
  |  June 7, 2024
ViewBag 101: How It Works, When It’s Used, Code Examples, and More

ViewBag is a property – considered a dynamic object – that enables you to share values dynamically between the controller and view within ASP.NET MVC applications. Let’s take a closer look at ViewBag, when it’s used, some limitations and other possible options to consider.

Ways to Pass Data from the Controller to the View

In the case of ASP.NET MVC, you have three ways to pass data from the controller to the view. These are:

  1. ViewBag
  2. ViewData
  3. TempData

ViewBag and ViewData are highly similar in the way they pass data from controller to view, and both are considered as a way to communicate between the view and the controller within a server call. Both of these objects work well when you use external data.

How does one differ from the other? 

ViewData is a dictionary or listing of objects that you can use to put data into. The data is now accessible to view. It is based on the ViewDataDictionary class. You can use ViewBag around any ViewData object so that you could assign dynamic properties to it, making it more flexible.

You would need typecasting for ViewData and check for null values, but you do not need to typecast complex data types in ViewBag.

The Microsoft Developer Network writes that the ViewBag property allows you to share values dynamically to the view from the controller

What is ViewBag?

The Microsoft Developer Network writes that the ViewBag property allows you to share values dynamically to the view from the controller. As such, ViewBag is considered a dynamic object without pre-set properties.

The syntax for using it in C# is:

public object ViewBag { get; }

For C++:

public:
property Object^ ViewBag {
	Object^ get();
}

Syntax For F#:

public object ViewBag { get; }

For VB:

Public ReadOnly Property ViewBag As Object

You can define the properties that you want by adding them, and you would need to use the same property name if you want to retrieve these values in view.

Here is a nifty example for that. In the controller, you can set up properties such as:

public ActionResult Index() //We'll set the ViewBag values in this action
{
ViewBag.Title = "Put your page title here";
ViewBag.Description = "Put your page description here";

ViewBag.UserNow = new User()
{
   Name = "Your Name",
   ID = 4,
};

return View();

}

To display these properties in view, you would need to use the same property names.

<h3>@ViewBag.Title</h3>

<p>@ViewBag.Description</p>

Your name:

<div>
<dl>
<dt>Name:</dt>
<dd>@ViewBag.UserNow.Name</dd>
<dt>ID:</dt>
<dd>@ViewBag.CurrentUser.ID</dd>
</dl>
</div>

A step-by-step demonstration is available at C# Corner.

When is It Used?

ViewBag is used to allow you to share values dynamically. There are several variables that are not known before the program is run, and these values are only entered during runtime. And this is where ViewBag shines, because you can put just about anything you want into it.

You can use ViewBag objects for transferring small amounts of data from the controller to the view, in cases such as:

  • Shopping carts
  • Dropdown lists options
  • Widgets
  • Aggregated data

ViewBag is a great way to access data that you use but may reside outside the data model. ViewBag is easy to use, because it’s implemented as a property of both controllers and view.

There is also one instance when ViewBag is mandatory, and that is when you are specifying a page title on any given view. For instance:

@{

ViewBag.PageTitle = "Page title will be displayed on the browser tab";

}

Some Limitations

As you may have guessed, ViewBag is not suitable for bigger sets of data or more complicated ones. For instance, complex relational data, big sets of aggregate data, data coming from a variety of sources and dashboards.

Also, there are some potential problems you may encounter. Errors, for instance, are not detected during compilation. Because of ViewBag’s dynamic nature, you can create names according to your liking. Dynamic properties are not checked during compilation, unlike normal types. What does this mean? You may not be able to detect if you used the right name and whether it matches the name you specified in the view.

For instance, you have assigned the following properties:

public ActionResult Index() //We'll set the ViewBag values in this action

{

ViewBag.Titl = "Enter your title here";

return View();

}

Then use this code for the view:

<h3>@ViewBag.Title</h3>

In this example, you specified Title as a ViewBag name, and this is a valid variable name for the property. But the view is looking for the variable name “Title.” When you compile your program, you would not be alerted to this error. Imagine having a lot of names to check manually!

ViewBag vs. TempData

TempData, on the other hand, is also a dictionary based on the TempDataDictionary class. TempData keeps information temporarily, as long as the HTTP request is active, and is perfect for redirects and a few other instances because of its temporary nature.

ViewModel

As discussed in the limitations section, there are several types of data where you cannot use ViewBag, primarily those big and complex data sets. For these types of data, you can use ViewModel if you are using ASP.NET MVC.

ViewModel also has a distinct advantage in that it is strongly typed. This means that unlike in ViewBag, ViewModel does not confuse one type with another type. For example, using ViewBag, the compiler will not detect an error when you use a DateTime as if it were a string.

public ActionResult Index() //We'll set the ViewBag values in this action
{
ViewBag.PageCreationDate = DateTime.Now;
ViewBag.LastIndexOfP = ViewBag.PageCreateDate.LastIndexOf('p');
return View();
}

The ViewBag property, LastIndexOfP in this case, is trying to get ‘p’ based on the PageCreationDate. In this example, you are treating a DateTime as a string, and compiling your program would not detect that error. Using ViewModel, you have better type protection, and error such as this one is detected by the compiler.

In general, ViewBag is a way to pass data from the controller to the view. It is a type object and is a dynamic property under the controller base class

Summary

In general, ViewBag is a way to pass data from the controller to the view. It is a type object and is a dynamic property under the controller base class. Compared to ViewData, it works similarly but is known to be a bit slower and was introduced in ASP.NET MVC 3.0 (ViewData was introduced in MVC 1.0).

The use of ViewBag has some limitations in that the compiler cannot check dynamic types and you would need to run your program first to find the errors when you use it. As such, using ViewModel is highly recommended in some instances.

ViewBag is a way to pass data from the controller to the view, but it does have a few limitations. You can build better when you understand ViewBag, when to use it, and what other options are available that may be better suited for certain use cases – such as ViewData (which is a bit faster) and ViewModel (when you need to check dynamic types).

If you want to write better ASP.NET applications, Stackify’s Prefix is a lightweight ASP.NET profiler that can help you write better software. And, if you want to take it up a notch, our APM tool offers the best in ASP.NET application monitoring. Check out our other tutorials for doing more with ASP.NET, such as understanding ASP.NET performance for reading incoming data, and find out what we learned while converting from ASP.NET to .NET Core in this post.

Additional Resources and Tutorials

For more information, check out the following resources and tutorials:

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More

Want to contribute to the Stackify blog?

If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]