When to use a view model in ASP.NET MVC?

Introduce the blog engine in ASP.NET MVC, where I want strongly typed views. I have a model for BlogPost and a model for comments. A typical page will display a blog post and all these comments on the post. Which object should I go to View ()? Should I create a view model? Maybe I'm misusing this term, but under this I should create a combined model for View () only, something like BlogAndComments? Should my controller create an instance of BlogAndComments and pas that?

Or, should I somehow pass the BlogPost and Comments object into the view?

+3
source share
4 answers

, . , View Model, , , " ". , , BlogPost ViewData. , , .

, . - "", , , . BlogViewPage, Title, BlogPost List.

, , BlogViewPage, , .

+4

, , .

BL , :

class CommentBO
{
    Guid UserID;
    string Text;
}

BO .

class PostBO
{
    Guid UserID;
    List<CommentBO> Comments;
}

.

class BlogModel
{
    string AuthorName;
    string BlogTitle;

    List<PostBO> Posts;
}

.

BO . , . . , , - , - .

+1

. , , , , . , , , . , , . , , . , , , .

+1

In my opinion, if the comments belong to the blog, why not create a collection of comments on the blog model? This makes sense in terms of domain modeling, and the likelihood that the ORM you use will support the lazy loading of this collection, which also simplifies your controller logic.

0
source

Source: https://habr.com/ru/post/1706706/


All Articles