ASP.net MVC - One ViewModel per View or per Action?

前端 未结 4 583
我寻月下人不归
我寻月下人不归 2020-12-31 07:27

Is it a better idea to have a single ViewModel per view or one per controller action?

Example:

public ProjectController : Controller
{
    public Act         


        
相关标签:
4条回答
  • 2020-12-31 07:45

    I follow this approach for basic forms:

    • One view model for the GET
    • One view model for the POST

    The GET model inherits the POST model.

    I will often pass a domain object to the GET model's constructor, and do 2 things with it:

    1. Populate the POST model properties with data from the domain object.
    2. Encapsulate the domain object as a local variable in the GET model. I use this for displaying some (read-only) data from the domain object. Saves a bit of effort. Some people will tell you not to do this.
    0 讨论(0)
  • 2020-12-31 07:50

    Use different model to receive input parameters in Post action (I don't even call it ViewModel in that case) than to pass output parameters to the view.

    That way you can customize exactly what input parameters do you accept.

    0 讨论(0)
  • 2020-12-31 07:54

    The correct answer

    Neither. There's no silver bullet and shouldn't be.

    The correct answer is therefore: use as many view models as your user interface process demands. That's regardless of views or controller actions.

    Sometimes an action demands a view, other a view. But don't follow some strict guidelines that would hinder your development. View models will come naturally as you develop your application. And should. Otherwise you may end up with unreasonable views that are based on some guideline you've set in stone.

    This is actually a similar answer as @DarinDimitrov's, but with a direct conclusion.

    0 讨论(0)
  • 2020-12-31 07:57

    Using a different view model for the GET and POST actions is the best and most flexible design. But using the same view model for the GET and POST actions also works in 90% of the cases and it is fine a good design. So if using the same view model works in your scenario don't hesitate to reuse it like this.

    In the case where different view models are used for the GET and POST actions there is still some relation between those classes: inheritance or composition.

    0 讨论(0)
提交回复
热议问题