Reputation: 441
there are two parts to this question
number 1:
im having receiving the same issue as in this post
the only diff is that im running in asp.net core v3.1
Dynamic Anonymous type in Razor causes RuntimeBinderException
ive tried the expando solution
but i still get the 'object' does not contain a definition for 'myproperty' err
heres my code
in controller:
var obj = new { newRoundNumber = maxround + 1 };
IDictionary<string, object> dict = new ExpandoObject();
dict.Add("p", obj);
var expando = StaticFunctions.ToExpando(dict);
return PartialView("_RoundsPartial", expando);
in partialview:
@{
var p = Model.p;
var newRound = p.newRoundNumber; <--- fails
for (var r = 1; r <= newRound; r++)
{
<div>@r</div>
}
}
can someone tell me whats up?
number 2:
apparently this used to work
new{
Project = projectInfo,
WorkItem = workitem
}.ToExpando());
but no longer in asp.net core v3.1
the conversion it allows is ToString()
does anyone know the equivalent in asp.net core?
UPDATE:
there was a comment response to try this link:
https://sebnilsson.com/blog/convert-c-anonymous-or-any-types-into-dynamic-expandoobject/
in short:
using System.Dynamic;
public static ExpandoObject ToExpandoObject(this object obj)
{
IDictionary expando = new ExpandoObject();
foreach (PropertyDescriptor property in
TypeDescriptor.GetProperties(obj.GetType()))
{
expando.Add(property.Name, property.GetValue(obj));
}
return (ExpandoObject) expando;
}
currently this returns in error on this line:
IDictionary expando = new ExpandoObject();
with:
cannot implicitly convert type ExpandoObject to IDictionary
and vice versa with the return
Upvotes: 0
Views: 516
Reputation: 166825
var expando = StaticFunctions.ToExpando(dict);
return PartialView("_RoundsPartial", dict);
Did you mean to pass in expando
and not dict
?
The extension method worked for me:
public static System.Dynamic.ExpandoObject ToExpandoObject(this object obj)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(obj.GetType()))
{
expando.Add(property.Name, property.GetValue(obj));
}
return (ExpandoObject)expando;
}
...but I got the same error "object does not contain a definition"
Upvotes: 0