0

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

GSerg
  • 76,472
  • 17
  • 159
  • 346
  • 1
    Create a view model with those 3 properties and project your query into a collection of the view model and return the view model to the view –  Apr 20 '17 at 12:08
  • 5
    Just create a View Model, don't be lazy – Milney Apr 20 '17 at 12:10
  • Hi , thanks for you answer i have already tried to create a new ViewModel , but i will use this methode often with different ViewModel so i think it's better to use an Anonymose object . – Arfaoui Hamouda Apr 20 '17 at 12:57

1 Answers1

0

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.

M. Wiśnicki
  • 6,094
  • 3
  • 23
  • 28