1

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!

4
  • @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 form
    – Sam
    Dec 8, 2022 at 16:39
  • I see now. I retracted my duplicate vote. 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. Dec 8, 2022 at 18:30
  • 1
    Can 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. Dec 8, 2022 at 20:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.