Steven
Steven

Reputation: 18859

MVC 3 - Display collection of items in rows

I have a collection that I'm displaying, like so:

@foreach (var employee in Model.Employees)
{
    <a href="#">@employee.Name</a>
}

This just displays everything in one long row. I'd like to display the collection in rows of 3, so that I have 3 items displayed, break to a new line, the next 3 items displayed, another break to a new line, and so on.

Is there a simple way to do this?

Upvotes: 1

Views: 2066

Answers (3)

Jonny Cundall
Jonny Cundall

Reputation: 2612

not using css, here's a simpleish way of doing this.

@{ var i = 0; }
@foreach (var employee in Model.Employees)
{
    @{ i++; } 
    <a href="#">@employee.Name</a>
    @if(i%3 == 2)
    {
        <br/>
    }
}

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156459

Mystere Man is right, and I typically use list items as the semantic markup elements for collections of links.

<ul>
@foreach (var employee in Model.Employees)
{
    <li><a href="#">@employee.Name</a></li>
}
</ul>

Then use CSS styling to make your list look how you want it to use (no bullet points, etc.) If you make the ul have a fixed with, and each li inside of each have a width of 1/3 of that, then make the lis show up as inline blocks, that ought to give you what you're going for. (jsfiddle)

Upvotes: 3

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

This has nothing to do with MVC, it's an HTML problem. You need to render HTML to make it do what you want. Look at the rendered output.

Typically you would wrap rows in divs or other elements in order to create the semantic markup you want.

Upvotes: 1

Related Questions