Cameron Gray
Cameron Gray

Reputation: 3

MVC5 - How to retrieve count of related rows to view?

new MVC programmer here. Really enjoying it so far, but I have been caught on a snag and I am hoping to get pointed in the right direction.

I have two tables in my Data Connections:

Guests - Id (Key)

Party - Id (Key)

Currently, I am returning the data from the Party table via a ViewModel into a View that displays a table which iterates through the rows of Party and displays the information for each row.

What I would like to do is get a COUNT of the rows where Party.Id = Guest.partyId, and return the count to that same view. So if Party A had three Guest and Party B had two guest, that would be reflected in my View.

Thanks!

Edited with code snippets:

Controller Index Method -

// GET: Parties
public ActionResult Index()
{
    var viewModel = new PartyViewModel
    {
    Parties = _context.Parties.ToList(),
    Guests = _context.Guests.ToList()
    };
    return View("Index",viewModel);
}

PartyViewModel -

public class PartyViewModel
{
    public IEnumerable<Party> Parties { get; set; }
    public IEnumerable<Guest> Guests { get; set; }
    public int guestCount { get; set; }
}

Table from Index view that I am populating:

<table class="table table-bordered table-hover">
<thead>
        <tr>
            <th>Party's Name</th>
            <th>Party Size</th>
            <th>RSVP</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var party in Model.Parties)
            {
            <tr>
                <td>@Html.ActionLink(party.Name, "EditPartyStatus", "Parties", new { id = party.Id }, null)</td>
                <td>INSERT COUNT HERE</td>
                <td>@party.isRSVP</td>
            </tr>
        }
    </tbody>
</table>

Screenshot of what im trying to do:

https://i.sstatic.net/CBlmA.jpg

Upvotes: 0

Views: 1335

Answers (1)

Marko
Marko

Reputation: 13263

Where you have "INSERT COUNT HERE" in your view just add the following line:

@Model.Guests.Count(g => g.PartyId == party.Id)

Upvotes: 1

Related Questions