I'm trying to make a simple Blog-application, but I'm a bit stuck on the architecture of the application.
I'd like to create a details-page with the content of the blog-post and a form for adding comment to the post.
My code looks like the following:
ViewModel
public class PostDetailsViewModel
{
[ValidateNever]
public Post Post { get; set; }
[Required]
public string Comment { get; set; }
[Required]
public string Author { get; set; }
}
Service-layer
public class BlogService {
public void AddComment(int postId, PostDetailsViewModel model) {
using(var context = new ApplicationDbContext()) {
Post post = context.Posts.Include(x => x.Comments).Single(x => x.Id == postId);
Comment comment = new Comment();
comment.Content = model.Content;
comment.Author = model.Author;
comment.TimeStamp = DateTime.Now;
post.Comments.Add(comment);
context.SaveChanges();
}
}
}
Controller
class BlogController{
public IActionResult Details(int id)
{
PostDetailsViewModel model = service.GetPostDetails(id);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Details(int id, PostDetailsViewModel model)
{
if (ModelState.IsValid)
{
service.AddComment(id, model);
return RedirectToAction("Details", new { id = id });
}
return View(model);
}
}
I already did a lot of research on architectural best-practices, but I can't see the wood for the trees anymore...
Could someone provide me with some best-practices/improvements on my architecture?
Thank you in advance!
-
@GregBurghardt: well, it doesn't really answer my question how to create a viewmodel that contains a) data to show in the view b) properties for model-binding in a formSam– Sam2022年12月08日 16:39:56 +00:00Commented Dec 8, 2022 at 16:39
-
I see now. I retracted my duplicate vote.Greg Burghardt– Greg Burghardt2022年12月08日 18:28:44 +00:00Commented Dec 8, 2022 at 18:28
-
Can you edit your question to include information from your last comment? Asking for "best practices" usually results in questions being closed as opinion-based or needing focus. The additional requirement of how to design this specific page for details and data entry might make this a better fit.Greg Burghardt– Greg Burghardt2022年12月08日 18:30:04 +00:00Commented Dec 8, 2022 at 18:30
-
1Can you focus your question on the problem you have with your current design? Asking for general feedback or best practices prevents the community from agreeing on a single objective answer.Greg Burghardt– Greg Burghardt2022年12月08日 20:04:40 +00:00Commented Dec 8, 2022 at 20:04