Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass multiple list from multiple models to view from controller

I tried finding a similar question, but none of them match to my scenario. So I am posting this as a new question. My Model and Controller looks like the following:

Model:

public class table1
{
     public string name1 { get; set; }
}

public class table2
{
     public string name2 { get; set; }
}

public class bothTable
{
     public table1 table1 { get; set; }
     public table2 table2 { get; set; }
}

Controller:

List<table1> list1 = //generate list from table1
List<table2> list2 = //generate list from table2

var model = ?

return View(model);

I just need a way to pass both the output list to the model so I can pass it on to the View. Obviously I have more than 1 property in both table1 and table2, and list1 and list2 are generated from LINQ so they have multiple results.

Can anyone please help me on what my model should look like so that I can pass both lists to my View?

I was refering to this link but it doesn't match exactly to my scenario: http://forums.asp.net/t/1998033.aspx?Passing+multiple+Models+to+View+from+Controller

I have also refereed to other similar questions in stackoverflow but I couldn't get the desired result.

like image 606
Bivo Kasaju Avatar asked Dec 24 '22 06:12

Bivo Kasaju


2 Answers

You should create a ViewModel that contains all the information you need in the view.

public class MyViewModel {
   public List<table1> TheFirstTable {get;set;}
   public List<table2> TheSecondTable {get;set;}
}

You can fill it like this

MyViewModel viewModel = new MyViewModel();
viewModel.TheFirstTable = //first table content
viewModel.TheSecondTable = //second table content
return View(viewmodel);

On the view you can then retreive the information from the model like

Model.TheFirstTable

or use it in a foreach loop

@foreach(var row in Model.TheFirstTable) {
    //do something with the row
}
like image 109
Tom Droste Avatar answered Dec 26 '22 19:12

Tom Droste


Change your model for bothTable to be List<table1> List<table2>. For example:

public class table1
{
     public string name1 { get; set; }
}

public class table2
{
     public string name2 { get; set; }
}

public class bothTable
{
     public List<table1> table1 { get; set; }
     public List<table2> table2 { get; set; }
}

Then, generate your model:

List<table1> list1 = //generate list from table1
List<table2> list2 = //generate list from table2

var model = new bothTable { table1 = list1, table2 = list2 };

return View(model);
like image 29
T. Frick Avatar answered Dec 26 '22 18:12

T. Frick