niico
niico

Reputation: 12809

What's the best practice for having 4 loops over same data in an MVC 4 view?

I have a view that contains 4 columns (HTML Divs). Each contains a different subset of the same data, based on my Place model (I'm just outputting the name property, there is also a category property - both strings).

I could create a ViewModel, containing 4 place models, each with the appropriate data in.

I could pass 4 strings with markup in (probably not good as mixing markup with data?).

What would be the best practice here?

(I also need to output the places in alphabetical order, by category - outputting a heading when the category changes - though this is a secondary requirement).

Upvotes: 0

Views: 138

Answers (1)

rae1
rae1

Reputation: 6144

You should probably use the first option, a ViewModel containing 4 PlaceViewModels. It will provide you with the flexibility of manipulating the objects and their properties, and display them as you want; and it will also improve maintenance of the view in the long run,

@model PlacesViewModel

@foreach (var place in Model.Places)
{
    // Render your HTML column here 
}

By passing a set of HTML strings (as mention in the second option) you won't be able to modify, inspect, parse, iterate or manipulate your objects in any useful way. You would be left to manipulate the strings using some sort of client-side framework, like jQuery.

However, if you simply want to iterate over a set of PlaceViewModel, you think about passing a list of them, and in your View do something like,

@model List<PlaceViewModel>

@foreach (var place in Model)
{
    // Render your HTML column here
}

which will save the need of having an extra class.

To order the models alphabetically by name (or any other property), do,

@foreach (var place in Model.Places.OrderBy(place => place.Name))
{
    // Render your HTML column here 
}

Upvotes: 1

Related Questions