0

How can i send two Model from controller to view using same action

2 Answers 2

2

Let's assume your two models are instances of MyModel and MyOtherModel.

I can think of two options:

  1. Pass MyModel as the Model and put MyOtherModel in the ViewBag.
  2. Create class MyBigModel with a property containing MyModel and another property containing MyOtherModel and pass MyBigModel as the Model.

Option 1 is really not your ideal solution. Since your model should relate to your view (that's why I prefer the name ViewModel), I'd really go for option 2.

Option 2 would look like this:

public class MyBigModel
{
    public MyModel { get; set; }
    public MyOtherModel { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Worth mentioning, option 1 is very bad and not recommended way of doing that.
2

Use ViewModel - create one more model that would contain both of the models, and send that to view

public class MyCustomViewModel
{
     public MyFirstModel First { get; set; }
     public MySecondModel Second { get; set; }
}

And in controller

public ActionResult Action()
{
     MyFirstModel first = new MyFirstModel();
     MySecondModel second = new MySecondModel();

     MyCustomViewModel model = new MyCustomViewModel();
     model.First = first;
     model.Second = second;

     return View(model);
}

Generally, as the name suggests, you should be using custom ViewModel for every view in your application, and then use tools like AutoMapper to map those view models back and forth to domain models. View models give you great flexibility in composing your view, as you can give any shape and form to them without changing domain.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.