Bashar Abu Shamaa
Bashar Abu Shamaa

Reputation: 2029

Reach/access a specific index in IEnumerable object in MVC

I need to access a specific item from IEnumerable @model ;

I know that I can reach all item by below code:

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

But I need to access the third item (as an example) by doing somthing like that : Model[3].FoodName

Are there are any way to reach a specific index item from IEnumerable object in MVC ?

Upvotes: 3

Views: 3020

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You could use the ElementAt(index) extension method:

Model.ElementAt(2)

Or change the model type from IEnumerable<T> to IList<T> or T[]:

@model IList<SomeViewModel>

now you could loop with an index:

@for (var i = 0; i < Model.Count; i++) 
{
    @Html.DisplayFor(x => x[i].FoodName)    
}

This is the preferred approach if you generate input fields (EditorFor, TextBoxFor, ...) because this way correct names will be assigned to them.

Upvotes: 8

Related Questions