veral
veral

Reputation: 67

How do I get property of an Ienumerable in the view?

enter image description hereI'm trying to grab the last four ImageUrl properties in my razor page for each item in each category.

I have a collection of categories that looks like this:

public class CategoryIndexModel
{
    public IEnumerable<CategoryModel> Categories { get; set; }
}

In that collection I have a collection of items as a property in this model:

public class CategoryModel
{
    public string CategoryName { get; set; }
    public int ListingQty { get; set; }
    public int SoldQty { get; set; }
    public string Notes { get; set; }

    public IEnumerable<InventoryItemModel> Items {get; set;}
}

Each item in the collection has a proeperty title, I want to access the most recently added 4 items and their properties in my view.

@foreach (var item in Model.Categories){
//display item.items[last].title, item.items[last-1].title, item.items[last-2].title 
}

Upvotes: 0

Views: 604

Answers (1)

Shane Parker
Shane Parker

Reputation: 36

I suspect the main problem you are encountering is the fact that indexing into IEnumerables is not possible. I would guess that IList may be a more appropriate interface for the Items, which would allow greater control over the items in general. However, it is possible to accomplish your goal without making any changes to your model.

You can get the last four titles via Linq with var lastFour = item.Items.Reverse().Take(4);.

To display in a comma separated list use @string.Join(", ", lastFour);.

Upvotes: 2

Related Questions