Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ActionResult 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.
like image 206
Dismissile Avatar asked Sep 13 '11 19:09

Dismissile


People also ask

Can we use 2 models in a view?

You can use multiple models in a single view by creating a common model for all the models that are to be used in a single view. To achieve this, refer to the following steps. First, create a new model (common for all models) and refer all other models that are to be used in the same view.

Can one view have multiple controllers?

Yes, It is possible to share a view across multiple controllers by putting a view into the shared folder. By doing like this, you can automatically make the view available across multiple controllers.

How many views does the model can have in MVC?

ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible.

How do I pass multiple models from view to controller?

Use a query parameter to denote which form is being posted. Use a different form name, but still with the view model. Use a redirect-only Action for the form (send new instances, and only part of the viewmodel) Use a mixture of the above.


1 Answers

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.

like image 197
Darin Dimitrov Avatar answered Oct 22 '22 01:10

Darin Dimitrov