Display List<dynamic> with Razor

2.8k Views Asked by At

I am using list of dynamic (anonymous objects) in a Razor view and display it.

Controller Code :

var res = (from c in _context.DM_Suivi_Us_Servis
                       group c by new { c.designation_magasin,c.designation_uf} into g
                       select new
                       {
                           g.Key.designation_magasin,
                           g.Key.designation_uf,
                           sum = g.Sum(c => c.nbr_us_servis),
                       }).ToList();

return View(res);

View Page (Razor view):

@model IEnumerable<dynamic>
@foreach (var item in Model)
{
    <tr>
        <td>@item.ToString()</td>
    </tr>
}

displays this result:

{ designation_magasin = CO3, designation_uf = NRG, sum = 65 }
{ designation_magasin = INC, designation_uf = NRG, sum = 0 } etc..

But when I try to display each item attribute:

@foreach (var item in Model)
{
    <tr>
        <td>@item.sum</td>
        <td>@item.designation_uf</td>
        <td>@item.designation_magasin</td>
    </tr>
}

I receive this following error

Error Screenshot

1

There are 1 best solutions below

1
M. Wiśnicki On BEST ANSWER

Create new view model :

public class YourName
{
    public string DesignationMagasin { get; set; }
    public string DesignationUf { get; set; }
    public int SumServis { get; set; }
}

And use projection

var res = (from c in _context.DM_Suivi_Us_Servis
            group c by new { c.designation_magasin, c.designation_uf } into g
            select new YourName
            {
                DesignationMagasin= g.Key.designation_magasin,
                DesignationUf= g.Key.designation_uf,
                SumServis= g.Sum(c => c.nbr_us_servis),
            }).ToList();

in view add @model List<YourName>

Here you find more about MVC.