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?
Create a parent view model that contains both models.
This way you can add additional models at a later date with very minimum effort.
Just create a single view Model with all the needed information in it, normaly what I do is create a model for every view so I can be specific on every view, either that or make a parent model and inherit it. OR make a model which includes both the views.
Personally I would just add them into one model but thats the way I do it:
Another way that is never talked about is Create a view in MSSQL with all the data you want to present. Then use LINQ to SQL or whatever to map it. In your controller return it to the view. Done.
Another option which doesn't have the need to create a custom Model is to use a Tuple<>.
It's not as clean as creating a new class which contains both, as per Andi's answer, but it is viable.
In fact there is a way to use two or more models on one view without wrapping them in a class that contains both.
Using Employee as an example model:
Is actually treated like.
So the View(employee) method is setting your model to the ViewBag and then the ViewEngine is casting it.
This means that,
Can be used like,
Essentially, you can use whatever is in your ViewBag as a "Model" because that's how it works anyway. I'm not saying that this is architecturally ideal, but it is possible.
You can use the presentation pattern http://martinfowler.com/eaaDev/PresentationModel.html
This presentation "View" model can contain both Person and Order, this new
class can be the model your view references.