public ActionResult TagManager(int id, AddTagPostViewModel vm) { try { List <Tag> previouslySelectedTags = _tagRepo.GetPostTags(id); List <int> previouslySelectedTagIds = new List <int>(); foreach (Tag tag in previouslySelectedTags) { previouslySelectedTagIds.Add(tag.Id); } if (vm.SelectedTagIds != null) { foreach (int tagId in vm.SelectedTagIds) { if (!previouslySelectedTagIds.Contains(tagId)) { _tagRepo.AddTagToPost(tagId, id); } } foreach (int tagId in previouslySelectedTagIds) { if (!vm.SelectedTagIds.Contains(tagId)) { _tagRepo.RemoveTagFromPost(tagId, id); } } } else { foreach (int tagId in previouslySelectedTagIds) { _tagRepo.RemoveTagFromPost(tagId, id); } } return(RedirectToAction("Details", "Post", new { id = id })); } catch (Exception) { return(RedirectToAction("Details", "Post", new { id = id })); } }
//GET: TagController public ActionResult TagManager(int Id) { //all tags List <Tag> tags = _tagRepo.GetAllTags(); //current tags that apply to post List <Tag> currentTags = _tagRepo.GetPostTags(Id); AddTagPostViewModel vm = new AddTagPostViewModel { Post = _postRepo.GetPostById(Id), Tags = _tagRepo.GetAllTags(), CurrentTagIds = new List <int>() }; foreach (Tag tag in currentTags) { vm.CurrentTagIds.Add(tag.Id); } return(View(vm)); }