public async Task <IActionResult> Edit(FanficEditViewModel fanficEditViewModel, int id) { try { fanficEditViewModel.FanficId = id; var fanfic = await _unitOfWork.Fanfic.GetByIdAsync(fanficEditViewModel.FanficId); fanfic.NameFanfic = fanficEditViewModel.NameFanfic; fanfic.Description = fanficEditViewModel.Description; var selectedTags = fanficEditViewModel.SelectedTags; var resultTags = fanfic.FanficsTags.Select(n => n.TagId.ToString()).ToList(); var addtags = selectedTags.Except(resultTags).ToList(); var removetags = resultTags.Except(selectedTags).ToList(); fanfic.FanficsTags = fanfic.FanficsTags .Where(x => !removetags.Contains(x.TagId.ToString())).ToList(); foreach (var item in addtags) { fanfic.FanficsTags.Add(new FanficTag() { TagId = Int32.Parse(item), FanficId = fanfic.FanficId }); } await _unitOfWork.SaveAsync(); return(Json(new{ isValid = true })); } catch { return(View()); } }
public async Task <IActionResult> Edit(int id) { var fanfic = await _unitOfWork.Fanfic.GetByIdAsync(id); var tags = await _unitOfWork.Tag.GetAllAsync(); var selectedTags = fanfic.FanficsTags.Select(x => new Tag() { TagId = x.Tag.TagId, TagTitle = x.Tag.TagTitle }); var selectList = new List <SelectListItem>(); tags.ForEach(i => selectList .Add(new SelectListItem( i.TagTitle, i.TagId.ToString(), selectedTags.Select(n => n.TagId) .Contains(i.TagId))) ); var viewmodel = new FanficEditViewModel() { FanficId = fanfic.FanficId, NameFanfic = fanfic.NameFanfic, Description = fanfic.Description, Tags = selectList }; return(View(viewmodel)); }