Search code examples
asp.net-mvcloopsviewbag

Show different button based upon ViewBags passed to Views from Controller?


I have created two ViewBags which contain different values.

ViewBag.attendingEvents = attendingIds;
ViewBag.notAttendingEvent = notAttendingIds;

The attendingIds contain the ids of all the users which are attending the event whereas notAttendingIds contain the ids of all the users which are not attending the event.

It's showing me too many button since I am looping through. If there are 100 users attending the event then its showing me 100 Remove buttons with one record because the loop. What's the best approach to solve this problem?

@foreach (var user in Model)
{
  <tr>
    <td>
        @Html.DisplayFor(modelItem => user.Name)
    </td>
    <td>
        @foreach(var record in ViewBag.attendingEvents as IList<User>) {<a href="#"> Remove </a>}
    </td>
  </tr>
}

Solution

  • This is my solution if I have understood your question correct and if you want only those users who attend the meeting to be able to have the remove button. You need to loop through the result of users and check if they exist in your attendable id list.

    @foreach (var user in Model.User)
    {
      <tr>
        <td>
            @Html.DisplayFor(modelItem => user.Name)
        </td>
        <td>
            @if(ViewBag.attendingEvents.Contains(user.Id))
                {<a href="#"> Remove </a>}
        </td>
      </tr>
    }