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?
If you are a fan of having very flat models, just to support the view, you should create a model specific to this particular view...
Many people use AutoMapper to map from their domain objects to their flat views.
The idea of the view model is that it just supports the view - nothing else. You have one per view to ensure that it only contains what is required for that view - not loads of properties that you want for other views.
you can't declare two model on one view, try to use
Html.Action("Person", "[YourController]")
&Html.Action("Order", "[YourController]")
.Good luck.
I hope you find it helpfull !!
i use ViewBag For Project and Model for task so in this way i am using two model in single view and in controller i defined viewbag's value or data
and in view tbltask and projectlist are my two diff models
@{
} @model List
ok, everyone is making sense and I took all the pieces and put them here to help newbies like myself that need beginning to end explanation.
You make your big class that holds 2 classes, as per @Andrew's answer.
Then in your controller you fill the 2 models. Sometimes you only need to fill one. Then in the return, you reference the big model and it will take the 2 inside with it to the View.
At the top of the View
Then load your inputs or displays referencing the big Models contents:
And. . . .back at the ranch, when the Post comes in, reference the Big Class:
and make use of what the model(s) returned:
Probably have some DataAnnotation Validation stuff in the class and probably put if(ModelState.IsValid) at the top of the save/edit block. . .
To use the tuple you need to do the following, in the view change the model to:
to use @html methods you need to do the following i.e:
or
Item1 indicates the first parameter passed to the Tupel method and you can use Item2 to access the second model and so on.
in your controller you need to create a variable of type Tuple and then pass it to the view:
Another example : Multiple models in a view