0

Is it possible to use multiple view model in same view?

I was trying to use a viewmodel using @model attribute

But i am stuck if i can use a second viewModel, where i put the second one?

SmartestVEGA
  • 8,415
  • 26
  • 86
  • 139
  • 1
    You can only have one `@model` declaration in the view (your view model can contain properties from multiple models) –  May 28 '18 at 14:15
  • 1
    The question could mean any number of things - can you use a composite ViewModel? Or can you use viewmodels interchangeably? Yes to both – Panagiotis Kanavos May 28 '18 at 14:15
  • "Multiple View Models" in its simplest form is *one* ViewModel with multiple properties. Those properties can be complex objects themselves – Panagiotis Kanavos May 28 '18 at 14:16
  • those question are related to models and my question is specific to viewmodel – SmartestVEGA May 28 '18 at 14:18
  • Can you use multiple models in place of each other? Yes again, as long as they inherit the same interface. You could also use dynamic typing. The view would work as long as all viewmodel instances have the same methods, properties – Panagiotis Kanavos May 28 '18 at 14:19
  • 1
    @SmartestVEGA no they don't. They are specific to *viewmodels*. Yes, you can have composite view models. Yes, you can have interchangeable viewmodels. You can also use an *array* as a ViewModel, allowing you to use multiple instances of the same ViewModel – Panagiotis Kanavos May 28 '18 at 14:19

1 Answers1

5

You can't send two view models in the same View.

As a quick workaround, you can create another class that wraps all the models you want to send in the view. By this way, you will benefit from a strongly typed view.

  public class Foo
  {
    public int ID { get; set; }
    public string Name { get; set; }
  }

  public class Bar
  {
    public int ID { get; set; }
    public string Name { get; set; }
  }

  public class FooBar
  {
    public Foo Foo { get; set; }
    public Bar Bar { get; set; }
  }

Inside your action method:

  var foo = new Foo
  {
    ID = 1,
    Name = "Foo"
  };

  var bar = new Bar
  {
    ID = 2,
    Name = "Bar"
  };

  var fooBar = new FooBar
  {
    Foo = foo,
    Bar = bar
  };

  return View(fooBar);