سلطان اليامي سلطان اليامي - 2 months ago 12
C# Question

How to Use an inside foreach use foreach in asp.net MVC C#

Can I view a table within a table in Razor
Ex:

foreach (var item in Model)
{
foreach (var item2 in Model2)
{
//I want to put here last table
}
}

Answer

Yes you can use a foreach loop inside a foreach loop. However you can only iterate over a property of your Model that implements IEnumerable interface. Take for instance this sample Model.

public class Team
{
    public int ID { get; set; }
    public string Name { get; set; }      
    public DateTime Founded { get; set; }
    public List<Member> Members { get; set; }
}

And Member.cs be

    public class Member
{
    public int ID { get; set; }
    public string FullNames { get; set; }
    public string Role { get; set; }
    public DateTime DateJoined { get; set; }
}

In your view, if you want to iterate over a collection of Teams and list the members names then you can do this

@model IEnumerable<Team>

 <table>
<thead>
    <tr>
        <th>@Html.DisplayNameFor(a => a.Name)</th>
        <th>@Html.DisplayNameFor(a => a.Founded)</th>
        <th>Players</th>
    </tr>
</thead>
    @foreach (var team in Model)
    {
        <tr>
            <td>@Html.DisplayFor(a => team.Name)</td>

            <td>@Html.DisplayFor(a => team.Founded)</td>

            <td>
                @foreach (var member in team.Members)
                {
                    <div>
                        @Html.DisplayFor(a => member.FullNames)
                    </div>
                }
            </td>

        </tr>        
    }        
</table>

As you can see, am iterating over all Teams displaying the Name and Founded details as well as a full names of members for each Team

Comments