James Wilson
James Wilson

Reputation: 5150

Dynamically show button in a foreach loop

I have two buttons in my foreach loop. I need both to appear unless it is the first item in the loop or the last item in the loop.

@foreach (var item in @Model.IPACS_Processes.IPACS_Procedures)
{
    <li class="span6">
        <img src="../../Images/thumbs/doc.png" alt="" class="pull-left" />
        <div class="comment-info">
            <h4>
                <a href="@Url.Action("ViewProcedure", new { id = item.procedureID })" data-original-title="@item.name">
                    @item.name</a></h4>
            <h5>
                <small>Owner: </small> <a href="javascript:void(0);">@item.owner</a></h5>
                <br />
            <p>
            @item.description
            </p>
            <br />
            <p>
                <a href="" class="btn btn-small"><span class="iconfa-double-angle-up icon-white">
                </span>Move Up</a>

                <a href="" class="btn btn-small"><span class="iconfa-double-angle-down"></span>
                    Move Down</a>
            </p>
        </div>
    </li>
    <br style="clear: both;" />
}

I need the "Move Up" button visible unless it is the first item in the loop, then I need the "Move Down" button visible unless it is the last item in the loop.

I'm not sure if setting up a count iterator is my only option, or if there is a cleaner way?

Upvotes: 2

Views: 354

Answers (1)

PizzaTheHut
PizzaTheHut

Reputation: 637

You can simply set an index and compare it against the upper and lower bounds of your array, or use the Count property of the array.

Something like this.

@{
  int i = 0;

  foreach (var item in Model.IPACS_Processes.IPACS_Procedures)
  {
    <!-- stuff and stuff --!>

    if(i > 0) {
            <a href="" class="btn btn-small"><span class="iconfa-double-angle-up icon-    white">
            </span>Move Up</a>
    }

    if(i < Model.IPACS_Processes.IPACS_Procedures.Count)
    {
            <a href="" class="btn btn-small"><span class="iconfa-double-angle-down">     </span>
                Move Down</a>
    }

    i++;

  }
}

Upvotes: 1

Related Questions