public ActionResult Edit([Bind(Include = "Content,Post_Id")] Post post) { var logic = new HiddenLogic(); post.AddingDate = _post.GetPostWithAddingDate(post); post.EditingDate = DateTime.Now; post.Votes = 0; if (ModelState.IsValid) { //content updated here _post.UpdateContentUpvotesAddDate(post); _post.SaveChanges(); //old tags: IList <PostTag> listPostTagsActual = _post.GetAllPostTagsByPostID(post.Post_Id); List <string> listOfTagNames = new List <string>(); foreach (var item in listPostTagsActual) { listOfTagNames.Add(_tag.GetTagNamesByTagID(item.Tag_Id)); } //list of tags used //tags updated //new content here bool check = false; bool removalCheck = true; MatchCollection matches = Regex.Matches(post.Content, @"\B(\#[a-zA-Z0-9-,_]+\b)"); //if post has tags if (post.PostTags != null) { foreach (var tag in matches) { if (listOfTagNames.Any(p => p.Contains(tag.ToString().ToLower()))) { logic.CheckTheDifferenceBetween(matches.Count, listOfTagNames.Count); continue; } else { AddTagAndPostTag(post, tag, removalCheck); } } //if there isnt any tag used //bool check if after edtiting theres nothing relative to tags if (check == false && matches.Count != 0) { bool enterLoop = true; var listOfMatches = new List <Tag>(); foreach (var tagFake in matches) { var tag2 = _tag.GetTagByName(tagFake.ToString()); listOfMatches.Add(tag2); } //remove from checklist, not postTags (if you try to remove only 1 and you will keep the second --failure) foreach (var item in listPostTagsActual) { //get tagID by match and remove the rest //if matchesTags exists in listOfTagsActual - leave it; //new list of tags foreach (var tag in listOfMatches) { if (listOfMatches.Any(x => x.Tag_Id == item.Tag_Id)) { enterLoop = false; } else { enterLoop = true; } if (enterLoop == true) { if (_tag.CheckIfPostTagExist(item.Tag_Id, post.Post_Id)) { _tag.RemovePostTag(item.Tag_Id, post.Post_Id); //get list of ID , remove postTag, remove tag if (_tag.IfPostOrCommentHaveTags(item.Tag_Id)) { _tag.RemoveTagsIfNotUsed(item.Tag_Id); _tag.SaveChanges(); } } } enterLoop = true; } } } else if (check == false && matches.Count == 0) { RemovePostandPostTag(post, listPostTagsActual); } } //if post is empty before and after is not else if (post.PostTags == null && matches != null) { removalCheck = false; foreach (var tag in matches) { AddTagAndPostTag(post, tag, removalCheck); } removalCheck = true; //if there isnt any tag used, bool check if after edtiting theres nothing relative to tags if (check == false) { RemovePostandPostTag(post, listPostTagsActual); } } return(RedirectToAction("Index")); } return(View(post)); }