即使在构造函数中初始化之后,SelectList也会抛出“对象引用未设置”错误

时间:2015-10-22 17:58:27

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我低于Model

public class UploadImageAlbum
{
    public UploadImageAlbum()
    {
       Albums = new SelectList(Enumerable.Empty<SelectListItem>());
    }
    public List<HttpPostedFileBase> Images { get; set; }

    public string AlbumID { get; set; }
    public SelectList Albums { get; set; }
}

public class Album
{
   public string AlbumID { get; set; }
   public string AlbumName { get; set; }
}

public class Repository
{
   public static List<Album> FetchAlbums()
   {
        List<Album> albums = new List<Album>
        {
            new Album(){ AlbumID = "Album1", AlbumName = "Album 1 desc"},
            new Album(){ AlbumID = "Album2", AlbumName = "Album 2 desc"}
        };
        return albums;
    }
}

我在名为UploadImageAlbum的单独模型中将此AdminViewModel称为“{1}},如下所示:

public class AdminViewModel
{
    public UploadImageAlbum UIAModel { get; set; }
}

并在Controller我尝试填写此model,如下所示:

public PartialViewResult GetMediaUploadView()
{
   AdminViewModel model = new AdminViewModel();
   List<Album> albums = Repository.FetchAlbums();
   model.UIAModel.Albums = new SelectList(albums, "AlbumID", "AlbumName");//Error here
   //Object reference not set to an instance of the object
   return PartialView("_UploadMedia", model);
}

我也试过

public PartialViewResult GetMediaUploadView()
{
   AdminViewModel model = new AdminViewModel();
        List<Album> albums = new List<Album>(); //Creating as new List
        albums = Repository.FetchAlbums();//then assign
        model.UIAModel.Albums = new SelectList(albums, "AlbumID", "AlbumName");
        return PartialView("_UploadMedia", model);
}

但是,我又得到了同样的错误。不知道是什么原因我得到这个错误,即使在模型级别和控制器级别初始化之后。希望有人可能对此有很好的了解。下面是我得到的错误的屏幕截图。

Screenshot

更新

我不认为这是重复的,因为我很清楚基于null reference的问题有很多,但我们得到null reference的级别是什么使这个问题与众不同。另外我的印象是,SelectList抛出错误,结果问题在这里有所不同。所以我坚持我的问​​题

1 个答案:

答案 0 :(得分:4)

您的AdminViewModel有财产:

public class AdminViewModel
{
    public UploadImageAlbum UIAModel { get; set; }
}

然后:

AdminViewModel model = new AdminViewModel();
//..
model.UIAModel.Albums = //...

您尚未初始化UIAModel,他会抛出错误。

如果你在C#6,你只需使用:

public class AdminViewModel
{
    public UploadImageAlbum UIAModel { get; set; } = new UploadImageAlbum();
}

快速修复