Question

I want the user to fill in 2 forms on the View. Each form should "represents" a Model. So the View should use 2 Models.

Do I need to implement a ViewModel or can I implement a View with 2 Models?

I already tried with Tuple<Item1, Item2> and failed

Was it helpful?

Solution

100% you should create a viewmodel that comprises of the two models you need.

public class MainViewModel
{
    public ModelA ModelA { get; set; }
    public ModelB ModelB { get; set; }
}

You should keep the association of one view -> one viewmodel class. I keep to this in my MVC apps, and it helps me keep the views simpler.

I would never try to mix two viewmodels in one view; that's making things tricker for yourself.

OTHER TIPS

This is exactly what a ViewModel is for.

A Model will generally represent a real world object, for example a Customer or an Order.

A ViewModel will be all of the information you need to display your view. That could (as in your case) be a combination of other models, some meta data or anything else.

So even if you could pass two models to your view (you can't, easily) then you shouldn't, a ViewModel is the correct thing to use.

yes, you should make a new viewmodel, which consists of the union of other 2 models. Also consider the mechanism of MVC (i,e, why models use, in what way models help, and why do we make them strongly type with views). This is why, models are for. It's also going to support you in a smooth way, while posting your form values to some action, decorated as [Httppost], because it is going to be difficult in case where you do not have a model, or have 2 different models. make something like:

public class UserRegModel
{
  public User UserModel{ get; set; }
  public Contact ConModel { get; set; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top