Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ViewBag be null in MVC4?

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?
}
like image 401
matthewpavkov Avatar asked May 30 '13 13:05

matthewpavkov


2 Answers

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;
    }
}
like image 187
SLaks Avatar answered Sep 21 '22 05:09

SLaks


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

if (ViewBag != null) 

is useless

like image 40
Raphaël Althaus Avatar answered Sep 20 '22 05:09

Raphaël Althaus