Let me start by saying that I know there are other ways to do this and I have already successfully done it other ways. But I got to wondering how to use @model IEnumerable<dynamic>
in a view.
I have tried this in the controller:
var result = from p in _db.People
join ps in _db.PersonSport on p.PersonId equals ps.PersonIdfk
join s in _db.Sports on ps.SportCodeFk equals s.SportCode
orderby s.SportName
where p.LastName == "Orr"
select new { p.FirstName, p.LastName, s.SportName };
return View(result);
With this in the view:
@model IEnumerable<dynamic>
<h4>Sports played by @Model.First().FirstName @Model.First().LastName:</h4>
@foreach (var item in Model) {
@item.SportName;<br />
}
And I get a runtime error
RuntimeBinderException: 'object' does not contain a definition for 'FirstName'
A breakpoint at the <h4>
shows that model has the data:
I tried using creating result as a new ExpandoObject()
and got the same error.
Am I way off base here or attempting something impossible? I was thinking of a use case where you have many table columns but are only extracting a few. Yes, I know I could create a class and do it that way, or send the data in ViewModel/ViewData, but was wondering if this was an option.