Hi @Coreysan ,
To display the complex model (as you said List of a List model) in the view, we can use nested @foreach
or @for
statement to loop the complex model. Like this:
@model WebApplication1.Data.cls_ListOfViewModel
<table class="table">
<thead>
<tr>
<th>
Customer Name
</th>
<th>
OrderDetails
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.myList) {
<tr>
<td>
@item.TheHeader.Name
</td>
<td>
@foreach(var childitem in item.TheDetails)
{
<ul>
<li>@childitem.ProductName ---- @childitem.Count.ToString()</li>
</ul>
}
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>
Based on your model, I create the cls_CustomerHeader
and cls_CustomerProduct
classes as below:
namespace WebApplication1.Data
{
public class cls_ListOfViewModel
{
public List<cls_OrderViewModel> myList { get; set; }
}
public class cls_OrderViewModel
{
public cls_CustomerHeader TheHeader { get; set; }
public List<cls_CustomerProduct> TheDetails { get; set; }
}
public class cls_CustomerHeader
{
public string Name { get; set; }
}
public class cls_CustomerProduct
{
public string ProductId { get; set; }
public string ProductName { get; set; }
public int Count { get; set; }
}
}
Then in the controller, set the initial data and return to the above view:
public IActionResult OrderDetails()
{
var initdata = new cls_ListOfViewModel()
{
myList = new List<cls_OrderViewModel>()
{
new cls_OrderViewModel(){
TheHeader= new cls_CustomerHeader(){ Name="Tom"},
TheDetails = new List<cls_CustomerProduct>()
{
new cls_CustomerProduct(){ ProductId="num1", ProductName="Pro A", Count=5 },
new cls_CustomerProduct(){ ProductId="num2", ProductName="Pro B", Count=7 },
new cls_CustomerProduct(){ ProductId="num3", ProductName="Pro C", Count=9 },
}
},
new cls_OrderViewModel(){
TheHeader= new cls_CustomerHeader(){ Name="Jack"},
TheDetails = new List<cls_CustomerProduct>()
{
new cls_CustomerProduct(){ ProductId="num4", ProductName="Pro D", Count=6 },
new cls_CustomerProduct(){ ProductId="num5", ProductName="Pro E", Count=2 },
new cls_CustomerProduct(){ ProductId="num6", ProductName="Pro F", Count=8 },
}
}
}
};
return View(initdata);
}
The result like this:
Besides, the official documentation has a tutorial (Tutorial: Read related data - ASP.NET MVC with EF Core) about read the related model and display it, might help you in the feature, you can refer to it.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion