Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialCecilia Benítez
1,396 Points¿how can I set two models in a single view?
I think this is an interesting question but I don't know how, maybe I have to make a model that returns all my models, does someone has a code example?
5 Answers
Steven Parker
231,264 PointsA "ViewModel" is a way to combine data from multiple data models, and optionally other sources, into a single representation that can be passed to a View, and received back from it.
I haven't seen this in a class here (but I have not taken them all), but you can find plenty references online, including this chapter in a Microsoft Tutorial.
Cheikh Faye Ndiaye
7,298 PointsHi this is a simple sample.
public class Model1{}
public class Model2{}
public class MyViewModel
{
public Model1 model1;
public Model2 model2;
public MyViewModel (Model1 mo1, Model2 mo2)
{
model1 =mo1;
model2=mo2;
}
}
Cecilia Benítez
1,396 Pointsthanks
Cecilia Benítez
1,396 Pointsam I doing something wrong in my Controller? '''C#
public class HomeController : Controller { private Modelo _modelos = null; public List<Receta> modelo1 = null; public Slide modelo2 = null;
public HomeController()
{
_modelos = new Modelo(modelo1, modelo2);
}
[HttpPost]
public ActionResult Index(Modelo modelo)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View(modelo);
}
public ActionResult Modelo(Modelo modelo)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View(modelo);
}
}
'''
Steven Parker
231,264 PointsIt looks like you've altered the controller's signature by giving it a constructor that requires arguments. Have you also altered the code that instantiates it to accommodate?
Cecilia Benítez
1,396 Pointssorry I the Controller shouldn't have any parameters, but I still don't know how can I make a repository of Models I only have 2 models but I don't know how to implement them, can I show you my proyect?
Steven Parker
231,264 PointsIt would probably be good to start a fresh question.
Cecilia Benítez
1,396 Pointshttps://github.com/PequeCeci/Guava.git here is my project, I made a model for making the slider dynamic but I already had another model so I don't know how to use both models in a ViewModel that contains both models.