which is the best place to implement data grouping in ASP.net MVC
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>
Grouping at the View level looks easy to implement but I want to avoid this is there a way to do this?
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.
You can do it however you like, frankly (one of the things I like about MVC, doesn't foist it's design decisions on you, generally), but many folks find this kind of transformation best done in the Controller, or more specficially by converting the model into a viewmodel.
Basicaly the idea is that if the Controller is sort of the go-between that translates user input into model actions and returns model data to the view in a usable way, then you would also do some kind of mapping there that handles translating the data from raw model into something the view recognizes.
So what i've seen done in the case you're doing is that some kind of logical model would be made in the same assembly as the Controllers, something (in your case) like:
public class RestarauntViewModel : IDictionary<string, IEnumerable<Restaraunt>>
{
public RestarauntViewModel(IEnumerable<Restaraunt>)
{
// your transform code that you had in the view
}
}
This keeps the view relatively clean and lets you change the logic of what's selected in each group, etc, as needed w/o touching any views that might use it.
精彩评论