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?
}
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;
}
}
ViewBag itself can't be null, so the first check
if (ViewBag != null)
is useless
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With