Two models in one view in ASP MVC 3

Smarty picture Smarty · Apr 5, 2011 · Viewed 175.5k times · Source

I have 2 models:

public class Person
{
    public int PersonID { get; set; }
    public string PersonName { get; set; }
}
public class Order
{
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

I want edit objects of BOTH classes in SINGLE view, so I need something like:

@model _try2models.Models.Person
@model _try2models.Models.Order

@using(Html.BeginForm())
{
    @Html.EditorFor(x => x.PersonID)
    @Html.EditorFor(x => x.PersonName)
    @Html.EditorFor(x=>x.OrderID)
    @Html.EditorFor(x => x.TotalSum)
}

This, of course, don't work: Only one 'model' statement is allowed in a .cshtml file. May be there is some workaround?

Answer

Andrew picture Andrew · Apr 5, 2011

Create a parent view model that contains both models.

public class MainPageModel{
    public Model1 Model1{get; set;}
    public Model2 Model2{get; set;}
}

This way you can add additional models at a later date with very minimum effort.