views:

20

answers:

1

I want to display list of items which belong to certain category like this:

Category I

  • Item 1
  • Item 2
  • Item 3

Category II

  • Item 6
  • Item 7

Category III

  • Item 10
  • Item 11
  • Item 12
  • Item 13

What is the best (and easiest) way to do this? I started doing this with two queries - one gets all goals, and then in foreach loop (in controller) I call another query which gets all items from this category, but then things got complicated... I have no idea in what type of object to store these items and how to pass all this together to a view.

Any idea?

Thanks!

+1  A: 

to select:

var query = from item in itemstable
group item by item.category into y
select new { key = y.Key, grouping = y };

then to access:

foreach(var g in query)
{
    //this is each grouping
    foreach(var item in query.grouping)
    {
        //this is each item in each group
    }
}
David
What is return type in this query? This looks pretty simple :)
ile
are you asking for the type of `query`? I think it's IEnumerable<IGrouping>
David
Yes, it works in LinqPAD, but I have no idea how to handle this in controller? Is there any tutorial about IGrouping?
ile
What am I suppose to inherit now in View?
ile
does this post help you? you probably don't want to group this in the controller because you would have to pass ViewData and the IEnumerable<IGrouping> to the view. Just do this grouping in the view's markup. http://stackoverflow.com/questions/1160420/how-do-i-group-data-in-an-asp-net-mvc-view/1160455
David
I still don't understand what does view inherit :)
ile
when you render the view from your controller, you can pass it whatever you want with the `View()` method. there are several overrides for this method, but you can pass it an object if you want. if you have additional data to be passed, and you insist on doing this grouping in the controller, I think you will have to either 1)adjust your model or 2)wrap your data and IEnumberanle<IGrouping> in an object and pass that as a whole.
David
Create a view model, and populate it on select like... select new CategoryGroup { Category = y.Key, Items = y }Then you can have a strongly typed view based on `CategoryGroup`
SteadyEddi