In my POST Edit function, I have my viewmodel that contain the game I want to update and list of platformIds that I want to add to the game.
Using this code, I was able to add platforms to my game but can't remove them. I put a breakpoint at the end and definitely see that viewModel.Game.Platforms have only what I selected but it is not updated in my game list.
If I add a few platforms and remove some at the same time. The new platforms get added but none are removed.
public ActionResult Edit(GameViewModel viewModel)
{
if (ModelState.IsValid)
{
List<Platform> platforms = new List<Platform>();
foreach (var id in viewModel.PostedPlatforms.PlatformIds)
{
platforms.Add(db.Platforms.Find(Int32.Parse(id)));
}
db.Games.Attach(viewModel.Game);
viewModel.Game.Platforms = platforms;
db.Entry(viewModel.Game).State = EntityState.Modified;
UpdateModel(viewModel.Game);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel.Game);
}
The model class is
public class Game
{
public int GameId { get; set; }
public string Title { get; set; }
public List<Platform> Platforms { get; set; }
}
public class Platform
{
public int PlatformId { get; set; }
public string Name { get; set; }
public List<Game> Games { get; set; }
}
Using ourmandave's suggestion, I got this code which while does change the platforms selection, it creates a new game entry every time which is inefficient and also increasing the id of the content which mess up bookmarks.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(GameViewModel viewModel)
{
if (ModelState.IsValid)
{
List<Platform> platforms = new List<Platform>();
if(viewModel.PostedPlatforms != null)
{
foreach (var id in viewModel.PostedPlatforms.PlatformIds)
{
platforms.Add(db.Platforms.Find(Int32.Parse(id)));
}
}
db.Games.Remove(db.Games.Find(viewModel.Game.PostId));
db.SaveChanges();
viewModel.Game.Platforms = platforms;
db.Games.Add(viewModel.Game);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel.Game);
}