I am trying to group a data collection and send it to the View where it needs another level of grouping I tried doing this in the Model level but looping throug the grouped collection becomes very difficult and determining the data type to pass to a partial is not easy
Grouping at the View level looks easy to implement but I want to avoid this is there a way to do this?
code: the model is a collection of Restaurants which should be grouped by category first and then by name to get different address
<% foreach (var categoryGroup in Model.GroupBy(r => r.RestaurantCategory)){%>
<h1><%=categoryGroup.Key %></h1>
<% foreach (var restaurant in categoryGroup.GroupBy(c => c.RestaurantName)){%>
<%Html.RenderPartial("Restaurant", restaurant); %>
<%}%>
<%}%>
Partial Code:
<ul class="addressList">
<%foreach (var address in Model){%>
<li>
<%= Html.Encode(address.Address1)%>
<%= Html.Encode(address.City)%>
<%=string.Format("<a href='http://www.bing.com/maps/default.aspx?where1={0}' target='_blank'> Get Directions</a>", address.FullAddress)%>
</li>
<%}%>
</ul>
Why is this a problem exactly? The model layer should not have implementation details for the view. It should simply have the data which is to be used by the view to present information to your users. There is no reason why another view couldn’t use the same model to display the data in a different manner. If you would like to do your data formatting somewhere other than the view, you need to add another layer, like an off shoot of the view model concept.
Since the view is displaying the data, do the grouping in the view. There are only a few reasons I might change that, most of which would be customer initiated.