public async Task <IActionResult> Post([FromBody] NewTopic topic) { try { if (ModelState.IsValid) { var category = _categoryService.GetById(topic.CategoryId); var user = _userManager.FindByIdAsync(topic.User.Id); topic.Category = category; topic.User = await user; if (_context.Topics.Any(t => t.Title == topic.Title)) { return(BadRequest("Topic with this title already exists")); } await _topicService.Add(topic); await _context.SaveChangesAsync(); } } catch (DataException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. return(BadRequest("Unable to save changes.")); } return(CreatedAtAction(nameof(Get), new { id = topic.Id }, topic)); }
public async Task <IActionResult> CreateTopicandPost(int id, NewTopicandPost topicandpost, NewTopic topic, NewPost post) { try { if (ModelState.IsValid) { var category = _categoryService.GetById(id); var userId = _userManager.GetUserId(User); var user = _userManager.FindByIdAsync(userId); topic.Category = category; topic.User = await user; topic.CategoryId = id; if (_context.Topics.Any(t => t.Title == topic.Title)) { ModelState.AddModelError("Topic.Title", "Topic with this title already exists"); return(View(topicandpost)); } await _topicService.Add(topic); post.User = await user; post.Topic = topic; if (_context.Posts.Any(p => p.Content == post.Content)) { ModelState.AddModelError("Post.Content", "Post with this content already exist"); return(View(topicandpost)); } await _postService.Add(post); return(RedirectToAction("PostsByTopic", "Posts", new { id = topic.Id })); } } catch (DataException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes."); } return(View(topicandpost)); }
public static int Add(TopicInfo topic) { ITopic dal = Factory <ITopic> .Create("Topic"); return(dal.Add(topic)); }