添加新选择列表项的对象引用错误

时间:2013-06-18 12:40:45

标签: c# asp.net-mvc list selectlistitem

我遇到List<SelectListItem>的问题。只要代码点击foreach,就会说:

object reference not set to an instance of an object.

我是否遗漏了某些内容,或者有人可以解释为什么会失败?

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
                    });

    }
}

2 个答案:

答案 0 :(得分:6)

之前是ViedoList初始化了吗?我认为不是。创建新列表向其添加项目,之后在模型中添加对它的引用:

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;

答案 1 :(得分:0)

可能你没有在VideoList类的无参数构造函数中初始化HammerpointVideoListModel,所以它不是一个空列表。

VideoList = new List<SelectedListItem>();

在构造函数中。