I make tags for news on a website. First use Entity Framework code. PostTag association table (PostId + TagId) is automatically generated. Here are my models:
public class Post { public int Id { get; set; } //... public virtual ICollection<Tag> Tags { get; set; } } public class Tag { public int Id { get; set; } //... public virtual ICollection<Post> Posts { get; set; } }
The problem is the action of the message editor for my admin panel. Create and delete actions work fine. Here is what I tried, it correctly updates all Post fields, but ignores tags.
[HttpPost, ValidateInput(false)] public ActionResult Edit(Post post, int[] TagId) { if (ModelState.IsValid) { post.Tags = new List<Tag> { }; if (TagId != null) foreach (int f in TagId) post.Tags.Add(db.Tags.Where(x => x.Id == f).First()); db.Entry(post).State = EntityState.Modified;
Decision
[HttpPost, ValidateInput(false)] public ActionResult Edit(Post post, int[] TagId) { if (ModelState.IsValid) { Post postAttached = db.Posts.Where(x => x.Id == post.Id).First(); post.Tags = postAttached.Tags; post.Tags.Clear(); if (TagId != null) foreach (int f in TagId) post.Tags.Add(db.Tags.Where(x => x.Id == f).First()); db.Entry(postAttached).CurrentValues.SetValues(post); db.SaveChanges(); return RedirectToAction("Index"); }
Thanks to gdoron for indicating the direction.
source share