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

前端 未结 4 615
我寻月下人不归
我寻月下人不归 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.

提交回复
热议问题