Question

I'm having a problem with the List<SelectListItem>. Whenever the code hits the foreach it says:

object reference not set to an instance of an object.

Am I missing something or can anyone explain why it is failing there?

public ActionResult HammerpointVideos(string category, string type)
{
    var stuff = Request.QueryString["category"];

    var ItemId = (from p in entities.EstimateItems
                  where p.ItemName == category
                  select p.EstimateItemId).FirstOrDefault();

    var Videos = (from e in entities.EstimateVideos
                  where e.EstimateItemId == ItemId
                  select new Models.HammerpointVideoModel
                  {
                      VideoName = e.VideoName,
                      VideoLink = e.VideoLink
                  }).ToList();

    var model= new Models.HammerpointVideoListModel();
    List<SelectListItem> list = model.VideoList;

    foreach (var video in Videos)
    {
        list.Add(new SelectListItem()
                    {
                        Selected=false,
                        Value = video.VideoLink,
                        Text = video.VideoName
                    });

    }
}
Was it helpful?

Solution

Is ViedoList initialized before? I assume it is not. Create new list add items to it and after that add reference to it in your model:

var model = new Models.HammerpointVideoListModel();
List<SelectListItem> list = new List<SelectListItem>();

foreach (var video in Videos)
{
    list.Add(new SelectListItem()
                {
                    Selected=false,
                    Value = video.VideoLink,
                    Text = video.VideoName
                });

}

model.VideoList = list;

OTHER TIPS

Probably You didn't initialized VideoList in the parameterless constructor of HammerpointVideoListModel class, so it is NOT an empty list.

Put

VideoList = new List<SelectedListItem>();

in the constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top