0

I have a problem when trying to print a linq query, after making the following query

var cargaDatos = (from rs in DB.C_gestcobcanalvendsem
                            group rs by new { rs.semana } into s
                            orderby s.Key
                            select new 
                            {
                              Semana = s.Key,
                              TotalDeuda = s.Sum(x => x.Credito)
                             }
                           ).ToList();

      return View(cargaDatos);

I try to print with the recommended way

<% foreach (var item in Model) { %>
    <tr>
        <td>
            <%: Html.DisplayFor(modelItem => item.Semana) %>
        </td>

<% } %>

or similar forms, but i don't find the form to print it. (possibly i'm doing something wrong but can not find the right way to manipulate the linq query whit 'group by clause').

regards

h40s4m4
  • 170
  • 1
  • 14
  • How did you define your Model for the View, you are returning an anonymous type from your controller. – Habib Jul 14 '14 at 17:25
  • I'm not defining directly (like php), ¿i need to define a type of? (and how to do this) – h40s4m4 Jul 14 '14 at 17:34

1 Answers1

0

You need to create a ViewModel such as:

//Call it whatever you want
public class ViewModel 
{
    // use whatever types Key and TotalDeuda are
    public int Semana { get; set; }
    public double TotalDeuda { get; set; }
}

Then you can use it in your linq query to make a strongly typed List:

   // Rest of linq as in your question
   select new ViewModel {
                           Semana = s.Key,
                           TotalDeuda = s.Sum(x => x.Credito)
                        }).ToList();

Then at the top of your View you need to put a @model or inherits declaration to define the model as strongly typed, set to IEnumberable<ViewModel> - or whatever you called the class.

Then you can show the two properties in your loop just using:

<%foreach (var item in Model)
    {  %>
<tr><td><%=item.Semana%></td>
<td><%=item.TotalDeuda%></td></tr>
<%} %>

Also it's easier using Razor syntax if you are able to look in to this. See article here for more info.

James P
  • 2,201
  • 2
  • 20
  • 30
  • i see, but, i can't use my actual class for this? or for each "grouped query" I must create a new model? – h40s4m4 Jul 14 '14 at 19:17
  • Yes, it is best to create a ViewModel if you are generating a result set that differs from your original class. For more information on ViewModels see [Here](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc), Or [Here](http://stackoverflow.com/questions/16548376/asp-net-mvc-how-exactly-to-use-view-models) - also for a more in depth look at how you can pass data in MVC see [here](http://www.codeproject.com/Articles/687061/Multiple-Models-in-a-View-in-ASP-NET-MVC-MVC). – James P Jul 14 '14 at 19:22
  • Thanks a lot, it's easier in symfony jajaja, close – h40s4m4 Jul 14 '14 at 19:24