Arnab
Arnab

Reputation: 2354

getting all values in list without iterating through them

In my controller, I'm returning returning View with a list of products.

return View(ProductList)

In my view I want to get all the values of the product list WITHOUT iterating through them either with a for each loop or any other way.

I need to do this as I'm going to design each Product differently in the view and I can't use a for each loop

The first productId is available using Model.Firstordefault().ProductId. Similarly I can get productName, productDescription and so on.

But how can I get the second productId to nth productId in the list?

Thanks Arnab .

Upvotes: 0

Views: 227

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038740

That's a great candidate for a display template. In your strongly typed view simply:

@model IEnumerable<ProductViewModel>
<table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        @Html.DisplayForModel()
    </tbody>
</table>

and then define a display template which will automatically be rendered for each element of the collection (~/Views/Shared/DisplayTemplates/ProductViewModel.cshtml):

@model ProductViewModel
<tr>
    <td>@Html.DisplayFor(x => x.Id)</td>
    <td>@Html.DisplayFor(x => x.Name)</td>
    <td>@Html.DisplayFor(x => x.Description)</td>
</tr>

Templated helpers work by conventions and you never have to write any loops in your views.

Upvotes: 1

Related Questions