'How to Bind a group by data in view in mvc5? what are the best ways to do
I am using Entityframework
context, i dont know how to bind to view.
I am grouping items by gender
public SQLChallengeEntities Sqlcontext = new SQLChallengeEntities();
var bookGrouped = Sqlcontext.Empinfoes.ToList()
.GroupBy(x => x.EmpSex).ToList();
return View(bookGrouped.ToList());
In View How to get the data
@foreach (var s in Model)
{
@group.Sex
foreach (var book in s.Values)
{
@s.Empname
@s.EmpDesignation @s.EmpAge
}
}
I am getting this error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[System.Linq.IGrouping2[System.String,AngularCrudS.Empinfo]]'
, but this dictionary requires a model item of type 'System.Linq.IGrouping2[System.String,AngularCrudS.Empinfo]'
Solution 1:[1]
In order to have @group.Sex
you need to have a model like
public class EmployeeSexGroupModel
{
public string Sex { get; set; }
public IEnumerable<AngularCrudS.Employee> Employees { get; set; }
}
Then your query would be
var bookGrouped = Sqlcontext.Empinfoes
.GroupBy(x => x.EmpSex).Select(x => new EmployeeSexGroupModel { Sex = x.Key, Employees = x});
return View(bookGrouped.ToList());
Your view would then look like
@model List<EmployeeSexGroupModel>
@foreach (var s in Model)
{
@s.Sex
foreach (var e in s.Employees)
{
@e.Empname
@e.EmpDesignation @e.EmpAge
}
}
Solution 2:[2]
public class GroupClass
{
public string Key { get; set; }
public List<Shahriar> shahriarList { get; set; }
}
var list = db.Shahriars.GroupBy(x => x.Name).Select(x => new GroupClass(){
Key = x.Key,
shahriarList = x.ToList()
}).ToList();
ViewBag.Data = list;
@foreach (var x in (List<GroupClass>)ViewBag.Data)
{
<tr><td colspan="4" style="background-color:lightblue;">@x.Key</td></tr>
foreach (var y in x.shahriarList)
{
<tr>
<td>@y.Id</td>
<td>@y.Name</td>
<td>@y.Roll</td>
<td>@y.Mobile</td>
</tr>
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | JamieD77 |
Solution 2 | Md Shahriar |