I’m trying to simply replace the generated Details method with a viewModel in a controller.
I know it should be simple, but I am getting an error when adding the .Find(id) action. I’m guessing it is a syntax thing, or the Find action doesnt works for viewModels, but cant find the answer anywere. Any help is much appreciated.
So trying to go from this:
public ViewResult Details(int id)
{
Artist artist = db.Artists.Find(id);
return View(artist);
}
To this
public ViewResult Details(int id)
{
var viewModel = new ArtistsDetailsVM();
viewModel.Artists = db.Artists.Find(id);
return View(viewModel);
}
Edit: to include viewModel:
public class ArtistsDetailsVM
{
public IEnumerable<Artist> Artists { get; set; }
public IEnumerable<Album> Albums { get; set; }
public IEnumerable<Song> Songs { get; set; }
}
ViewModels are usually used when you want to composite a bunch of data from multiple models, collections, lookup lists, etc, into a strongly typed ViewModel object that you can reference in the View.
So if you want to use a ViewModel here you have two options; you can either use an automapper (which is overkill here), or you can make sure your “Artists” property on your ArtistsDefailtsVM matches the type returned by db.Artists.Find().
Can you post the code for ArtistsDefailtsVM, and the error your’re getting? It seems like .Find(id) returns a single Artist, but your VM’s “Artists” property name implies a collection. That might be the source of your error.