1

I am doing a left outer join in Entity Framework and sending the output in a ViewBag to display in a table. However, nothing is displayed in a View. My code is below.

        var clients = db.Client
                .Include("ClientInformation")
                .Where(t => t.IsApplicationRegistered == false)
                .Take(20);

        var q = (from c in clients
                join a in db.Agent
                on c.AgentUserId equals a.AgentUserId into jointable
                from x in jointable.DefaultIfEmpty()
                select new 
                { 
                    c.ClientId,
                    c.ClientInformation.FirstName,
                    c.ClientInformation.FamilyName,
                    c.ClientInformation.Address,
                    AgentFirstName = x.FirstName,
                    AgentLastName = x.LastName
                }).ToList();

        ViewBag.clients = q;

This retrieves the results (I can see them via IntelliSense during debug) but the view does not display anything. The sample view is below.

@foreach (dynamic item in ViewBag.clients)
    {
        <tr>
            <td>@item.FirstName @item.FamilyName</td>
            <td>@item.Address</td>
            <td>@item.AgentFirstName @item.AgentLastName</td>
        </tr>
    }

Any ideas? Thanks.

UPDATE:

Inside the View I get an exception

'object' does not contain a definition for 'FirstName'

However, I can clearly see that it is there, when I hover over item inside foreach loop.

sakura-bloom
  • 4,524
  • 7
  • 46
  • 61

1 Answers1

1

My question was answered here: dynamic type in mvc view

You cannot use anonymous types as models. The reason for this is because the compiler emits anonymous types as internal. This means that they are only accessible withing the current assembly. But as you know Razor views are compiled by the ASP.NET runtime as separate assemblies which have no way of using those anonymous types.

Obviously the correct way in this case is to use a view model.

So, I'll just use a View Model.

More great info on this is here: Dynamic Anonymous type in Razor causes RuntimeBinderException

Community
  • 1
  • 1
sakura-bloom
  • 4,524
  • 7
  • 46
  • 61