Search code examples
c#asp.net-mvc-4asp.net-mvc-viewmodel

Do I have to implement a ViewModel when using multiple Models in one View?


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


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.