Reputation: 2293
I'm trying to populate this IEnumerable with values from a db.
I can't see what I'm doing wrong.
IEnumerable<Categories> categories = new List<Categories>();
List<SelectListItem> catItems = new List<SelectListItem>();
foreach (var cats in categories)
{
catItems.Add(new SelectListItem
{
Text = cats.CategoryName,
Value = cats.CategoryID.ToString()
});
}
Here is the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace SportsStore.Domain.Entities
{
public class Categories
{
[Key]
public int CategoryID { get; set; }
public string CategoryName { get; set; }
}
}
Upvotes: 0
Views: 87
Reputation: 7605
Because here you create a new (and empty) list of Categories:
IEnumerable<Categories> categories = new List<Categories>();
and here you try to iterate over the empty list:
foreach (var cats in categories)
{
Which means you're never adding anything to cat.Items
Upvotes: 0
Reputation: 51494
How are you populating the categories list? It won't just get filled by saying...
IEnumerable<Categories> categories = new List<Categories>();
You need populate it somehow.
Upvotes: 2
Reputation: 245419
You only ever initialize a new collection of categories, there are never any added to the collection.
Upvotes: 7