Question

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?
}
Was it helpful?

Solution

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;
    }
}

OTHER TIPS

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

if (ViewBag != null) 

is useless

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top