1

What's the proper way to check in Razor if ViewBag has a value set? I know that I can do

if(ViewBag.Foo != null) {
  ...
}

But looking in the events stream in VS 2015 I notice this generates a (handled) RuntimeBinderException.

The fact that this throws an error leads me to suspect that this is not the correct way to check the presence of a value, and is actually harming performance (though I have not done any testing). In addition it doesn't help you distinguish between a value being absent and the value being set to null.

Is there a more correct approach?

Community
  • 1
  • 1
George Mauer
  • 117,483
  • 131
  • 382
  • 612
  • 1
    This is not razor-specific, it's just a dynamic member. See http://stackoverflow.com/questions/2998954/dynamic-how-to-test-if-a-property-is-available, http://stackoverflow.com/questions/9956648/how-do-i-check-if-a-property-exists-on-a-dynamic-anonymous-type-in-c, http://stackoverflow.com/questions/2839598/how-to-detect-if-a-property-exists-on-an-expandoobject, http://stackoverflow.com/questions/10899613/dynamic-object-how-to-tell-if-a-property-is-defined – CodeCaster Aug 30 '15 at 19:41
  • That's a good point @CodeCaster - kinda surprised at the awkwardness of all those approaches – George Mauer Aug 30 '15 at 19:43

1 Answers1

-1

There is no way defined by razor developers, however you can see this to do it by yourself using extension method.

Community
  • 1
  • 1
Lali
  • 2,816
  • 4
  • 30
  • 47
  • Well nothing about that **requires** an extension method - its all just c# and will actually **not work** as an extension method since you can't extend a dynamic. I appreciate the find of the link though. – George Mauer Aug 30 '15 at 19:43
  • The post I shared states what you said in your comment and the accepted answer in the post addresses 'dynamic' nature issue. – Lali Aug 30 '15 at 19:46