C
C#15mo ago
Alizer

❔ what the proper way to check if ``dynamic`` has a specific property?

I have this code below
dynamic modelObject = new { Count = 0 };
dynamic modelObject = new { Count = 0 };
now I'm passing this as a @model to a partial view
@model dynamic

<div class="container-fluid">
<p>
<!-- Check if @@Model has a property named ``Count`` -->
</p>
</div>
@model dynamic

<div class="container-fluid">
<p>
<!-- Check if @@Model has a property named ``Count`` -->
</p>
</div>
how do i properly check if modelObject has a property named Count? I searched for solutions online and most require me to turn it into a Dictionary BUT I DONT WANT TO DO THAT!! casting it to dictionary is just....redundant and doesn't feel right, anyways, is there a proper way to do it?
9 Replies
Tvde1
Tvde115mo ago
The whole point about dynamic is that you lose any and all type information and safety
Alizer
Alizer15mo ago
yeah but the data i send to this specific partial view vary a lot if i make a class/struct just for the model it would contain 50+ properties
Tvde1
Tvde115mo ago
Some googling recommends
var hasCount = modelObject.GetType().GetProperty("Count") != null;
var hasCount = modelObject.GetType().GetProperty("Count") != null;
sounds like a weird page a dictionary does sound like a good use case then
Alizer
Alizer15mo ago
oh boy Rider bugs out, it thinkgs .GetType() is a member of the dynamic object, alright ill try this out
Mayor McCheese
Mayor McCheese15mo ago
Something like strategy pattern on the page might help too, depending on type of object youll render parts of razor differently
Tvde1
Tvde115mo ago
.GetType() is a member of the dynamic object dynamically I suppose which probably yields another dynamic
Mayor McCheese
Mayor McCheese15mo ago
Down side is probably lots of duplication on page, sounds like you're building some sort of control renderer?
Alizer
Alizer15mo ago
alright so I went for this code which for some reason automatically checks for null, thanks btw
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.