yondaimehokage
yondaimehokage

Reputation: 253

Sending a List to View to iterate over

I tried searching SO, but maybe I'm not using the right search terms.

Basically, I first need to generate a list in my controller that would contain something like this:

Item 1: name = 'cat', category = 'animal'
Item 2: name = 'dog', category = 'animal'
Item 3: name = 'tulip', category = 'plant'

And so on. So when I get to my view I can do a:

@foreach (item in list)
{
    if (category == "animal")
    {
        @item.name<br />
    }
}

How do I build the list in the controller?

Upvotes: 0

Views: 31

Answers (1)

David
David

Reputation: 218827

The same way you build any list. Let's say you have a class defining your items and we'll call it MyModel. (In this case I'll assume it has string properties Name and Category.) Then you'd build a list of that object:

var models = new List<MyModel>();

And you can add any number of items you like to that list:

models.Add(new MyModel { Name = "Cat", Category = "Animal" });
models.Add(...);
// etc.

Then send it to the view:

return View(models);

In the view you'd declare that as your model type:

@model List<MyModel>

And can then iterate over it in the view:

@foreach (var item in Model)
{
    if (item.Category == "animal")
    {
        @item.Name<br />
    }
}

A List<T> is no different from any other model type. You can build one and send it to your view like any other model.


Edit: For the purpose of this example, the MyModel class was:

public class MyModel
{
    public string Name { get; set; }
    public string Category { get; set; }
}

Naturally, you'll want to use a more meaningful name than MyModel.

Upvotes: 2

Related Questions