开发者

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

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

Example:

public ProjectController : Controller
{
    public ActionResult Edit(int id)
    {
        var project = ...;

        return View(new ProjectEditViewModel(project));
    }

    [HttpPost]
    public ActionResult Edit(ProjectEditViewModel model)
    {
    }

    **OR**

    [HttpPost]
    public ActionResult Edit(Project model)
    {
    }

    [HttpPost]
    public Acti开发者_Python百科onResult Edit(ProjectEditPostViewModel model)
    {
    }
}

Here are the three options, which is best?

  1. Use the same ViewModel for my POST/GET actions.
  2. Use a ViewModel for my GET action and my domain model for my POST action.
  3. Use a different ViewModel for GET and a different ViewModel for POST.


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.


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜