Edit and create blog posts

This commit is contained in:
Robert Marshall 2020-01-03 10:47:13 +00:00
parent 47431d4650
commit 44875a6a45
6 changed files with 126 additions and 1 deletions

View file

@ -3,13 +3,14 @@ using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Website.Data;
using Website.Models;
using Website.ViewModels;
namespace Website.Controllers
{
public class BlogController : Controller
{
const int MaxPostsPerPage = 10;
private const int MaxPostsPerPage = 10;
private readonly BlogRepository _repo;
public BlogController(BlogRepository repo)
@ -36,5 +37,35 @@ namespace Website.Controllers
return NotFound();
}
}
public async Task<IActionResult> Edit(int? id) {
if (!id.HasValue)
return View();
try {
var post = await _repo.GetPostByIdAsync(id.Value);
var model = new BlogPostSubmission {
Id = post.Id,
Title = post.Title,
Content = post.Draft
};
return View(model);
}
catch (InvalidOperationException) {
return NotFound();
}
}
[HttpPost]
public async Task<IActionResult> Save(BlogPostSubmission submission) {
var post = submission.Id.HasValue ? await _repo.GetPostByIdAsync(submission.Id.Value) : new BlogPost();
post.UpdateTitle(submission.Title);
post.UpdateDraft(submission.Content);
var savedPost = await _repo.SavePost(post);
return RedirectToAction(nameof(Edit), new{savedPost.Id});
}
}
}