简体   繁体   English

在asp.net mvc4中通过查询打印linq组

[英]print a linq group by query in asp.net mvc4

I have a problem when trying to print a linq query, after making the following query 进行以下查询后,尝试打印linq查询时出现问题

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'). (可能我在做错事,但找不到正确的方式来处理linq查询“ group by子句”)。

regards 问候

You need to create a ViewModel such as: 您需要创建一个ViewModel,例如:

//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: 然后,您可以在linq查询中使用它来创建一个强类型列表:

   // 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. 然后,在View的顶部,您需要放置@model或继承声明以将模型定义为强类型,设置为IEnumberable<ViewModel> -或您所谓的类。

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. 此外,如果您可以查看,则使用Razor语法会更容易。 See article here for more info. 有关更多信息,请参见此处的文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM