What is ViewBag?

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

Stackify Developer Tips, Tricks & Resources Leave a Comment

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.

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, it 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();
}

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?

It 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 it shines, because you can put just about anything you want in ViewBag.

You can use ViewBag objects for small amounts of data, transferring it from the controller to the view. It will work well for such cases as:

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

It’s a great way to access data that you use but may reside outside the data model. It is also 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, it’s 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 when using it. Errors, for instance, are not detected during compilation. Because of its dynamic nature, you can create ViewBag 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!

Other Options

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 and
  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.

ViewBag vs. TempData

TempData, on the other hand, is also a dictionary and it is based on the TempDataDictionary class. It keeps information temporarily, as long as the HTTP request is active. TempData 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. 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.

Additional Resources and Tutorials

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

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.

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).


Free Download