|
-
Feb 3rd, 2015, 03:28 PM
#1
Thread Starter
Member
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 .
Last edited by kender; Feb 3rd, 2015 at 04:07 PM.
-
Feb 3rd, 2015, 07:26 PM
#2
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.
-
Feb 7th, 2015, 08:10 AM
#3
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;}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|