开发者

ASP.NET MVC - Passing Grouped data into a View

I've got a LINQ to SQL object, and I want to group the selected data and then pass it into a view. What's the correct way of doing this? I'm sure I need to group the data when I select it rather than grouping it in the view, as this will result in about 200 rather 50000 rows I need to pass into my view. Are there any good examples of this online that anyone has seen?

Cheers

MH


-----edit-----

I want a bit of both:- for example, my data object has (amongst others) 2 properties I want to extract, and group on, ItemDetail.ItemID and ItemDetail.Label - it is a set of th开发者_Go百科ose I want to pass into my view. My data factory returns a IQueryable which will contain (in live) about 100 records for each ItemID/Label combination, and thus I want to group this in my view so that it only shows 1 row per ItemID/Label combination. Also, how do I type my View - I have tried passing in something like the var xxx = ...; return View(xxx); but I'm not sure how to strongly type (if I can) the view properly. I can probably boj this and get it working, but I wanted to do this correctly.


----edit 2----

I've just got a bit further on this. using the var IQueryable itemDetList itemDetList = itemDetList.OrderBy(i => i.ItemID).GroupBy(i => i.ItemID).Select(i => i.First()); produces a grouped list, with 1 row per ItemID, and preserves the object typing so that I can pass it into a strongly-typed view - is that the correct way of manipulating the data? How can I put another layer of grouping so that it groups by .Label within each .ItemID group?


You may want to abstract the model you pass to your view from the LINQ 2 SQL objects; check out the View Model Pattern. If this means you find yourself potentially writing lots of code to map properties from LINQ 2 SQL objects to your View Model objects then consider using AutoMapper.


Well, then group the data and pass it onto your View from your Controller...

public ViewResult Foo()
{
    var data = this.GetGroupedData();
    return this.View(data);
}

private IEnumerable<Bar> GetGroupedData()
{
    return from x in GetData()
           group x by x.Baz into g
           select new Bar(g.Key);
}


I would define Presentation-Models that represent your groups in your View. Fill the Presentation-Models with LINQ and pass them to your View.

With Presentation-Models you have strongly typed data to display in your view.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜