Brent Arias
Brent Arias

Reputation: 30215

Using 'Dynamic' to Assist Anonymous Types

I want the ability to grab an anonymous type from my view, that was established by the corresponding controller. According to this article, such an ability becomes possible in C# 4.0 with the 'dynamic' keyword. However, when I try to find an actual example I find answers ranging from it kinda 'is possible' to it kinda 'is not possible.'

In my case, I have a controller creating this:

XElement headings = XElement.Parse(part.TagList);
var items = from heading in headings.Descendants("heading")
            select new {
                name = heading.Attribute("name").Value, 
                tags = heading.Attribute("tags").Value,
                content = shapeHelper.List() //This is a dynamic object!!!
            }; //can I add 'as dynamic;' here????

In short it would be nice if, without a static type, my view could simply reach into the model like this:

@{
//Currently this next line returns an error saying that 
//'object' contains no method 'Count'
int foo = Model.items.Count();  

//This 'foreach' works.
foreach(dynamic lineItem in Model.items){
  //But this does not work. Gives another "'object' has no definition for 'name'"
  <p>@lineItem.name</p>     }
}

Possible?

Upvotes: 0

Views: 264

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245489

Not sure it's exactly what you're looking for, but you could always use the ViewBag:

Controller

ViewBag.Items = from heading in headings.Descendants("heading")
                select new {
                    name = heading.Attribute("name").Value, 
                    tags = heading.Attribute("tags").Value,
                    content = shapeHelper.List()
                };

View

ViewBag.Items.First().content;

Upvotes: 2

Related Questions