AnonyMouse
AnonyMouse

Reputation: 18630

mvc viewmodels saving

Hi I'm going through the tutorial at:

http://www.asp.net/mvc/tutorials/mvc-music-store-part-1

Instead of using the ViewBag I was trying to get it to use viewModels.

The create GET became:

public ActionResult Create()
{
    return View();
} 

The create POST now has an AlbumViewModel:

[HttpPost]
public ActionResult Create(AlbumViewModel albumViewModel)
{
    if (ModelState.IsValid)
    {
        //db.Albums.Add(albumViewModel);
        //db.SaveChanges();
        return RedirectToAction("Index");  
    }

    return View(albumViewModel);
}

The ViewModel is to contain the Genres dropdownlist instead of passing them with the ViewBag.

The AlbumViewModel class is:

public class AlbumViewModel
{
   public Album Album { get; set;}
   public SelectList Genres = new SelectList(repository.Genres, "Name", "Id");
}

As you can see from the Create Post I'm unsure how to save the newly created album with GenreId.

Can someone please tell me how you do this?

Upvotes: 2

Views: 1304

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You would have to map your view model back to the EF domain model (Album) in order to save the changes. Personally I use AutoMapper to achieve this task as it simplifies much of the coding.

[HttpPost]
public ActionResult Create(AlbumViewModel albumViewModel)
{
    if (ModelState.IsValid)
    {
        var album = Mapper.Map<AlbumViewModel, Album>(albumViewModel);
        db.Albums.Add(album);
        db.SaveChanges();
        return RedirectToAction("Index");  
    }

    return View(albumViewModel);
}

Also in your GET action you should be passing the view model to the view or chances are that you will get NRE when you try to render the dropdownlist:

public ActionResult Create()
{
    var albumViewModel = new AlbumViewModel();
    return View(albumViewModel);
} 

Upvotes: 4

Related Questions