开发者

Grouping in Entity Framework MVC

Hi all i've currently got a list of telephone numbers being output using:-

Controller:-

public ActionResult ViewSubRange(int id)
{
    IEnumerable<Number> numbers = context.Numbers.Where(m => m.RangeID == id).ToList();

    return View("SubRange", numbers);
}

View:-

@model IEnumerable<TelephoneNumberManagement.Models.Number>
<table>
    <tr>
        <th>
            Number
        </th>
  开发者_如何学运维      <th>
            Status
        </th>
    </tr>

@foreach (var item in Model)
{
    <tr> 
        <td>@item.Number1</td>
        <td>@item.Status.StatusName</td>
    </tr> 

}

</table>

This is fine, however i've noticed that we can have a lot of numbers being output. I was wondering if its possible to group the numbers, so for example by Customer. So what i want to achieve is something like:-

01132210000-01132210999 CUSTOMER A

01132211000-01132211009 CUSTOMER B

01132211010-01132211029 CUSTOMER C


You could define a new view model:

public class MyViewModel
{
    public string StatusName { get; set; }
    public string Numbers { get; set; }
}

and then group by customer name:

public ActionResult ViewSubRange(int id) 
{
    var numbers = context.Numbers
        .Where(m => m.RangeID == id)
        .GroupBy(x => x.Status.StatusName)
        .Select(x => new MyViewModel
        {
            StatusName = x.Key,

            // TODO: could change the format if you will or
            // select the min and max or whatever you need
            Numbers = string.Join("-", x.Select(n => n.Number1)) 
        })
        .ToList();
    return View(numbers);
}

and finally in your view:

@model IEnumerable<MyViewModel>
<table>
    <tr>
        <th>Number</th>
        <th>Status</th>
    </tr>

    @foreach (var item in Model)
    {
        <tr> 
            <td>@item.Numbers</td>
            <td>@item.StatusName</td>
        </tr> 
    }
</table>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜