[HttpPost]
public ActionResult Create(Playlist playlist)
{
if (ModelState.IsValid)
{
if (Session["Playlist"] != null)
{
List<int> musicIds = new List<int>();
musicIds = Session["Playlist"] as List<int>;
if (musicIds.Count > 0)
{
UserProfileRepository UserProfileRepository = new UserProfileRepository(db);
string Name = this.User.Identity.Name;
UserProfile User = UserProfileRepository.getModelByName(Name);
playlist.UserId = User.UserId;
db.Playlists.Add(playlist);
db.SaveChanges();
foreach (var item in musicIds)
{
Music music = db.Musics.Find(item);
/*
* Error in the line below, it says:
* Object reference not set to an instance of an object.
* */
playlist.Musics.Add(music);
}
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
return View(playlist);
}
大家好,有人能告诉我的代码有什么问题吗? 当播放列表和音乐都被实例化时,我似乎无法弄清楚它为什么说“对象引用未设置为对象的实例。”
提前致谢!
答案 0 :(得分:1)
这意味着playlist.Musics
为空
您应该在构造函数中初始化它。