How to check if ViewBag has a certain dynamically created property or not?
Folks,
Suppsoe that a certain dynamic property of a ViewBag object is optional. How can I check whether it has been created or not?
My first reaction is to check for null value.
Code:
@if (ViewBag.OptProp != null) {...}
But then how to handle the case when the property has been actually created, but the value assigned to it is null ?
Any suggestion, insight or reference is really appreciated!
Cheers,
- Nick
p.s. I think, my question is similar to this one: How do I check if an object has a property in JavaScript?. Except mine is about .NET .
Re: How to check if ViewBag has a certain dynamically created property or not?
How do you usually determine whether an object has a property in C#? Using Reflection. You'd start with ViewBag.GetType().GetProperty(...).
That said, I'd suggest that you use two properties. The first would be the value for OptProp and the second would be whether or not OptProp has been set, if you really need to distinguish between not set and set to null. You can then do this:
Code:
@if (ViewBag.IsOptPropSet && ViewBag.OptProp != null)
The controller action must then ALWAYS set IsOptPropSet to either true or false and, if true, it must then set OptProp.
Re: How to check if ViewBag has a certain dynamically created property or not?
If you have multiple fields you can create a methode, that uses reflection, just like jmcilhinney said:
Code:
public static bool HasProperty (object obj, string propertyName)
{
var result = false;
var dynamic = obj as DynamicObject;
if(dynamic == null)
{
result = false;
}
else
{
result = dynamic.GetDynamicMemberNames().Contains(propertyName);
}
return result;}