我低于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);
}
但是,我又得到了同样的错误。不知道是什么原因我得到这个错误,即使在模型级别和控制器级别初始化之后。希望有人可能对此有很好的了解。下面是我得到的错误的屏幕截图。
更新
我不认为这是重复的,因为我很清楚基于null reference
的问题有很多,但我们得到null reference
的级别是什么使这个问题与众不同。另外我的印象是,SelectList
抛出错误,结果问题在这里有所不同。所以我坚持我的问题
答案 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();
}
快速修复