Issue with using two models in the view in ASP.NET MVC [duplicate]
Clash Royale CLAN TAG#URR8PPP
Issue with using two models in the view in ASP.NET MVC [duplicate]
This question already has an answer here:
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?
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
You need to use a a
ViewModel
as @maccettura already mentioned. Here is an example stackoverflow.com/a/50509915/2946329– S.Akbari
Aug 7 at 19:25
ViewModel
2 Answers
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.
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;
You need to make a ViewModel that contains both things as properties. You can only use one Model in a view
– maccettura
Aug 7 at 19:24