【问题标题】:How to Bind a group by data in view in mvc5? what are the best ways to do如何在mvc5中按数据绑定组?最好的方法是什么
【发布时间】:2015-09-26 09:22:10
【问题描述】:

我正在使用Entityframework 上下文,我不知道如何绑定到视图。

我正在按性别对项目进行分组

public SQLChallengeEntities Sqlcontext = new SQLChallengeEntities();

var bookGrouped = Sqlcontext.Empinfoes.ToList()
.GroupBy(x => x.EmpSex).ToList();

return View(bookGrouped.ToList());

查看如何获取数据

   @foreach (var s in Model)
   { 
        @group.Sex 
        foreach (var book in s.Values) 
        { 
            @s.Empname
            @s.EmpDesignation @s.EmpAge 
        }
   }

我收到此错误:

传入字典的模型项的类型是'System.Collections.Generic.List1[System.Linq.IGrouping2[System.String,Angular‌​CrudS.Empinfo]]',但是这个字典需要一个'System.Linq.IGrouping2[System.String,AngularCrudS.Empinfo]'类型的模型项

【问题讨论】:

  • 分组后你期望得到什么?
  • @teovankot; OP 期望有@group.Sex
  • 删除所有 .ToList() 调用。
  • 我只是按 Empdesignation 分组,但我已经分组并存储在 var bookGrouped = Sqlcontext.Empinfoes.ToList() .GroupBy(x => x.EmpDesignation);返回视图(bookGrouped);但是当我去查看时出现错误如何将其传递给查看,为什么查看不获取数据
  • 请在问题的视图中显示您正在使用的模型。 @model ModelClassHere

标签: asp.net asp.net-mvc linq asp.net-mvc-5


【解决方案1】:

为了拥有@group.Sex,你需要有一个像

这样的模型
public class EmployeeSexGroupModel
{
    public string Sex { get; set; }
    public IEnumerable<AngularCrudS.Employee> Employees { get; set; }
}

那么您的查询将是

var bookGrouped = Sqlcontext.Empinfoes
    .GroupBy(x => x.EmpSex).Select(x => new EmployeeSexGroupModel { Sex = x.Key, Employees = x});

return View(bookGrouped.ToList());

你的视图看起来像

@model List<EmployeeSexGroupModel>
@foreach (var s in Model)
{
    @s.Sex
    foreach (var e in s.Employees)
    {
        @e.Empname
        @e.EmpDesignation @e.EmpAge
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 2013-04-05
    相关资源
    最近更新 更多