public async Task <IActionResult> Create(PostsVm posts, string[] TagPosts) { if (TagPosts != null) { posts.TagPosts = new List <TagPosts>(); foreach (var tag in TagPosts) { var tagToAdd = new TagPosts { TagId = Convert.ToInt32(tag), PostId = posts.PostId }; posts.TagPosts.Add(tagToAdd); } } if (ModelState.IsValid) { Posts model = _mapper.Map <Posts>(posts); DateTime date = DateTime.Now; model.DateCreated = date; _context.AddPost(model); _context.Commit(); return(RedirectToAction(nameof(Index))); } ViewData["CategoryId"] = new SelectList(_context.GetCategoryList(), "CategoryId", "Title", posts.CategoryId); ViewData["Tags"] = new MultiSelectList(_context.GetTagList().AsEnumerable(), "TagId", "Title", posts.TagPosts.Select(e => e.TagId).AsEnumerable()); return(View(posts)); }
public async Task <IActionResult> Edit(int id, PostsVm posts, string[] SelectedTags) { if (id != posts.PostId) { return(NotFound()); } var model = _context.GetPost(id); if (SelectedTags != null) { var tags = model.TagPosts; var remove_items = _context.GetTagPostList().Where(e => e.PostId == model.PostId); foreach (var tag in remove_items) { _context.DeleteTagPost(tag); } _context.Commit(); foreach (var tag in SelectedTags) { var tagToAdd = new TagPosts { TagId = Convert.ToInt32(tag), PostId = posts.PostId }; model.TagPosts.Add(tagToAdd); } } if (ModelState.IsValid) { try { DateTime date = DateTime.Now; model.DateCreated = date; _context.UpdatePost(model); _context.Commit(); } catch (DbUpdateConcurrencyException) { if (!PostsExists(posts.PostId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["CategoryId"] = new SelectList(_context.GetCategoryList(), "CategoryId", "Title", posts.CategoryId); ViewData["Tags"] = new SelectList(_context.GetTagList(), "TagId", "Title"); return(View(posts)); }
// GET: Posts/Edit/5 public async Task <IActionResult> Edit(int?id) { if (id == null) { return(NotFound()); } var posts = _context.GetPost(id); PostsVm vm = _mapper.Map <PostsVm>(posts); if (posts == null) { return(NotFound()); } vm.SelectedTags = posts.TagPosts.Select(e => e.TagId).AsEnumerable(); ViewData["CategoryId"] = new SelectList(_context.GetCategoryList(), "CategoryId", "Title", posts.CategoryId); ViewData["Tags"] = new MultiSelectList(_context.GetTagList().AsEnumerable(), "TagId", "Title"); return(View(vm)); }