Pass LINQ anomyous type results like a collection of property bags to a ASP.NET 5 MVC View

235 Views Asked by At

I've searched around and people talk about using ExpandDo with dynamic, but I haven't been able to figure it out how to do this with a collection returned from a LINQ query.

I'm doing an inner join on my database between 2 tables (student and enrollments)

    var innerJoin =
        from e in db.Enrollments
        join s in db.Student on e.StudentID equals s.StudentID
        select new { Student= s.Name , Course = e.CourseID };

I've tried

dynamic model = innerJoin.ToList().ToExpando();

return View(model)

and I have

@model System.Collections.Generic.IEnumerable<dynamic>

at the top of my View.cshtml

but that gives this error when I try navigating to the controller in the web application:

The model item passed into the dictionary is of type 'System.Dynamic.ExpandoObject', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[System.Object]'. ''

I also tried:

   dynamic model = innerJoin.ToList();

    return View(model);

but then in my view (.cshtml file) I

    @foreach (dynamic item in Model)
    {
        <tr>
            <td>
                @Html.Raw(item.Course)
            </td>
        </tr>
    }

it'll barf on the @Html.Raw line with

An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in App_Web_index.cshtml.1bbec3a6.jtomobws.dll but was not handled in user code

Ideally I'd like to make it a one liner. In my view I'm hoping to be able to iterate over a collection of property bags, and extract the Student and Course fields. So my property bag would contain properties Student and Course, and they'd be a collection of them. I've looked at many similar posts, but none have done this

Thanks Thomas

1

There are 1 best solutions below

1
On

EDITED

I assume that innerJoin.ToList().ToExpando(); converts the list of your anonymous objects returned from the join into Expando object and not to IEnumerable<dynamic>. If you want to get List of dynamic objects you can use something like:

var innerJoin = from e in db.Enrollments
                join s in db.Student on e.StudentID equals s.StudentID
                select e;


var model = new List<dynamic>();
foreach(var l in innerJoin)
{
    dynamic temp = new System.Dynamic.ExpandoObject();
    temp.Student = l.StudentID;
    temp.Course = l.CourseID;
    model.Add(temp);
}

This will work for System.Collections.Generic.IEnumerable<dynamic> model

Here is the example for working fiddle

Although I really advise you to use strongly typed models. By using dynamic objects you basically giving up on most of the advantages of statically typed languages.