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.
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
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With