1

我遇到了问题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
                    });

    }
}
4

2 回答 2

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;
于 2013-06-18T12:46:43.903 回答
0

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

VideoList = new List<SelectedListItem>();

在构造函数中。

于 2013-06-18T12:44:41.503 回答