Mic
Mic

Reputation: 79

Display results of Model in For Loop instead of Foreach Asp MVC 5

Ok so I basically have a survey wizard with 4 parts in it, I need to display 5 separate results into each, but a for loop as below, will obviously display all results and will therefore break the wizard, how can I loop through this in a for loop? Any help will be greatly appreciated, thanks

@foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Category.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Survey.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>       
        </tr>
    }

Upvotes: 2

Views: 5590

Answers (2)

AmmarCSE
AmmarCSE

Reputation: 30557

Assuming your Model is some sort of IENumerable

@{ var list = Model.ToList();
for (int i = 0; i < list.Count; i++)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => list[i].Category.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => list[i].Survey.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => list[i].Title)
            </td>       
        </tr>
    }
 }

Upvotes: 2

Mic
Mic

Reputation: 79

Go it, just used an incrementer, seems to work just fine with the Model

 @{
        int counter = 0;
        foreach (var item in Model)
        {
            counter++;
            if (counter > 1 && counter < 6)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Category.Title)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Survey.Title)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Title)
                    </td>
                </tr>
            }
        }
    }

Upvotes: 1

Related Questions