public IActionResult AddCategory(CategoryViewModel category) { if (!ModelState.IsValid) { return(View(category)); } try { if (category.Id == 0) { var cat = new Category { Name = category.Name }; _context.Add(cat); _context.SaveChanges(); } else { var cat = _context.Category.Find(category.Id); cat.Name = category.Name; _context.Update(cat); _context.SaveChanges(); } } catch (Exception ex) { throw ex; } return(RedirectToAction("Index")); }
public void UpdatePostCategory(int postId, int catId, int newCatId) { try { var postCategory = _context.PostsCategory .Where(x => x.CategoryId == catId && x.PostId == postId) .FirstOrDefault(); postCategory.CategoryId = newCatId; _context.Update(postCategory); _context.SaveChanges(); } catch (Exception ex) { throw ex; } }
public IActionResult AddPost(PostViewModel model) { if (!ModelState.IsValid) { return(View(model)); } try { var post = new Post(); if (model.Id == 0) { post = new Post { Id = model.Id, Title = model.Title, ShortDescription = model.ShortDescription, LongDescription = model.LongDescription, UserId = _userManager.GetUserId(User), PublishDate = DateTime.UtcNow }; _context.Add(post); _context.SaveChanges(); foreach (var item in model.Categories) { _postService.AddPostCategory(post.Id, item); } if (model.MainPhoto != null && model.MainPhoto.Length > 0) { _postService.UploadImage(model.MainPhoto, post.Id); } } else { post = _postService.GetPost(model.Id); post.Title = model.Title; post.ShortDescription = model.ShortDescription; post.LongDescription = model.LongDescription; post.PublishDate = model.PublishDate; var newPost = new List <PostsCategory>(); for (int i = 0; i < model.Categories.Count; i++) { newPost.Add(new PostsCategory { PostId = post.Id, CategoryId = model.Categories[i] }); } post.PostsCategory = newPost; _context.Update(post); _context.SaveChanges(); if (model.MainPhoto != null && model.MainPhoto.Length > 0) { _photoService.ChangeMainPhotoToFalse(post.Id); _postService.UploadImage(model.MainPhoto, post.Id); } } if (model.Photos != null) { _postService.UploadImage(model.Photos, post.Id); } } catch (Exception ex) { throw ex; } return(Redirect(Url.Action("UserProfile", "User"))); }