0

I am trying to use two models in my view, but I am get an error saying that only one model can be used. I get the purpose of why only one model can be used but are there any workarounds so I could use two models in my view. I have listed the code below.

Controller:

/* Parts Method */
public ActionResult Parts()
{
    return View(db.Part.ToList());
}

View:

@model Inventory_System.Models.Transaction @model IQueryable

The first model is for connecting to the view model and the second is connecting to a database list from the controller to be displayed. How could I use both of these models in the same view?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kaleb Meeks
  • 111
  • 1
  • 1
  • 9
  • 4
    You need to make a _ViewModel_ that contains both things as properties. You can only use one Model in a view – maccettura Aug 07 '18 at 19:24
  • You need to use a a `ViewModel` as @maccettura already mentioned. Here is an example https://stackoverflow.com/a/50509915/2946329 – Salah Akbari Aug 07 '18 at 19:25

2 Answers2

2

You should create a composite model with two properties.

View Model

public class CompositeModel
{
  public Transaction  Transaction {get;set}
  public List<Part> ListOfParts {get;set}   
}

Controller

 public ActionResult Parts()
{
   CompositeModel model = new CompositeModel
   {
     Transaction = new Transaction();
     ListOfParts = db.Part.ToList();
   };
   return View(model);
}

View

@model /*Name Space*/.CompositeModel;

I think that is good solution.

Dejan Ciev
  • 142
  • 4
0

You should create a ViewModel that contains your two models

public class ViewModel()
{
    public Inventory_System.Models.Transaction Transaction {get;set;}
    public IQueryable<Inventory_System.Models.Part> Part {get;set;}

}
AntoOne
  • 99
  • 10