In MVC
, sometimes I'm setting specific property of ViewBag
according to some condition.For example:
if(someCondition)
{
// do some work
ViewBag.SomeProperty = values;
}
return View();
In my View
I'm checking whether the property is null like this:
@if(ViewBag.SomeProperty != null)
{
...
}
Until now I was thinking that should throw an exception because if my condition is not satisfied then SomeProperty
is never get set.And that's why I was always using an else
statement to set that property to null
.But I just noticed, it doesn't throw an exception even if the property doesn't exists.For example in a Console Application
if I do the following, I'm getting a RuntimeBinderException
:
dynamic dynamicVariable = new {Name = "Foo"};
if(dynamicVariable.Surname != null) Console.WriteLine(dynamicVariable.Surname);
But it doesn't happen when it comes to ViewBag
.What's the difference ?
AFAIK the ViewBag
is a dynamic wrapper around ViewData
. And ViewData
itself retrieves the values as follows:
public object this[string key]
{
get
{
object value;
_innerDictionary.TryGetValue(key, out value);
return value;
}
set { _innerDictionary[key] = value; }
}
hence, if key doesn't exist it returns default value for type and doesn't throw exception.
ViewBag inherits from DynamicViewDataDictionary which returns null for missing properties.
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