public ActionResult AddCategoryToPost(PostViewModel model) { var post = _blogRepository.GetPostById(model.ID); var postCats = _blogRepository.GetPostCategories(post); List<string> pCatIds = new List<string>(); foreach (var pCat in postCats) { pCatIds.Add(pCat.Id); } var newCats = model.Categories.Where(x => x.Checked == true).ToList(); List<string> nCatIds = new List<string>(); foreach (var pCat in newCats) { nCatIds.Add(pCat.Id); } if (!pCatIds.SequenceEqual(nCatIds)) { foreach (var pCat in postCats) { _blogRepository.RemovePostCategories(model.ID, pCat.Id); } foreach (var cat in model.Categories) { PostCategory postCategory = new PostCategory(); if (cat.Checked == true) { postCategory.PostId = model.ID; postCategory.CategoryId = cat.Id; postCategory.Checked = true; _blogRepository.AddPostCategories(postCategory); } } _blogRepository.Save(); } return RedirectToAction("EditPost", new { slug = post.UrlSeo }); }
public void AddPostCategories(PostCategory postCategory) { _context.PostCategories.Add(postCategory); }