Can ViewBag be null in MVC4?
Asked Answered
J

2

8

In MVC4, is it possible for ViewBag to ever be null? If so, under what scenarios could it be? If not, how do you know?

Specifically, I want to know if it can be null in a view. However, additional information about whether it can be null in a controller would be useful.

For example, do I need to perform a null check?

if (ViewBag != null && ViewBag.Something != null && ViewBag.Something.Foo == "Bar")
{
    // can ViewBag be null?
}
Jarvisjary answered 30/5, 2013 at 13:23 Comment(2)
In a view or in a controller?Thermoplastic
Either I suppose, but specifically in a view.Jarvisjary
T
17

No, it can't.

The ViewBag property getter in WebViewPage looks like this:

public dynamic ViewBag
{
    get
    {
        if (_dynamicViewData == null)
        {
            _dynamicViewData = new DynamicViewDataDictionary(() => ViewData);
        }
        return _dynamicViewData;
    }
}
Thermoplastic answered 30/5, 2013 at 13:27 Comment(1)
I tried tracking this down myself, however all I could find is public dynamic ViewBag { get; } in ViewMasterPage. How did you locate this?Jarvisjary
G
5

ViewBag itself can't be null, so the first check

if (ViewBag != null) 

is useless

Geometer answered 30/5, 2013 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.