MVC Error: Object reference not set to an instance of an object

First you need to add properties in your view model to hold selected artist and selected genre:

public class StoreManagerViewModel
{
    public Album Album { get; set; }
    public int? SelectedArtistId { get; set; }
    public List<Artist> Artists { get; set; }
    public int? SelectedGenreId { get; set; }
    public List<Genre> Genres { get; set; }
}

Then in your Edit.aspx view instead of:

<%: Html.EditorFor(model => model.Album,
    new { Artists = Model.Artists, Genres = Model.Genres }) %>

You could simply:

<%: Html.EditorForModel() %>

and in your editor template ~/Views/Home/EditorTemplates/Album.ascx:

<%@ Import Namespace ="MvcMovies1" %>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMovies1.Models.Album>" %>

<p>
    <%: Html.LabelFor(model => model.Title) %>
    <%: Html.TextAreaFor(model => model.Title) %>
    <%: Html.ValidationMessageFor(model => model.Title) %>
</p>

<p>
    <%: Html.LabelFor(model => model.Price) %>
    <%: Html.TextAreaFor(model => model.Price) %>
    <%: Html.ValidationMessageFor(model => model.Price) %>
</p>

<p>
    <%: Html.LabelFor(model => model.AlbumArtUrl) %>
    <%: Html.TextAreaFor(model => model.AlbumArtUrl) %>
    <%: Html.ValidationMessageFor(model => model.AlbumArtUrl) %>
</p>

and in your editor template ~/Views/Home/EditorTemplates/StoreManagerViewModel:

<%@ Import Namespace ="MvcMovies1" %>
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMovies1.ViewModels.StoreManagerViewModel>" %>

<%: Html.EditorFor(model => model.Album) %>

<p>
    <%: Html.LabelFor(model => model.SelectedArtistId) %>
    <%: Html.DropDownListFor(model => model.SelectedArtistId, new SelectList(Model.Artists, "ArtistId", "Name")) %>
</p>

<p>
    <%: Html.LabelFor(model => model.SelectedGenreId) %>
    <%: Html.DropDownListFor(model => model.SelectedGenreId, new SelectList(Model.Genres, "GenreId", "Name")) %>
</p>

<div>
    <%: Html.ActionLink("Back to List", "Index") %>
</div>

Does Album have an ArtistId since in that line you are calling Model.ArtistId and if Album doesn't have that property on it you will get a null reference exception. That's because the Model is a shorthand for the object that is strongly typed to your view, which happens to be Album in your case.

There is no where in your above code where you are setting the ViewData["Artists"]. Are you setting that anywhere since that could be your issue too.

EDIT

Set the ViewData in the action and it should work:

public ActionResult Edit(int id)
{
     var viewModel = new StoreManagerViewModel
     {
         Album = storeDB.Albums.SingleOrDefault(a => a.AlbumId == id),
         Genres = storeDB.Genres.ToList(),
         Artists = storeDB.Artists.ToList()
     };

     ViewData["Artists"] = storeDB.Artists.ToList();
     ViewData["Genres"] = storeDB.Genres.ToList();

     return View(viewModel);
 }

Tags:

C#

Asp.Net Mvc