Bootstrap collapse within a foreach loop

2020-04-11 12:39发布

问题:

I am having trouble getting the collapsible panels to work within my foreach loop. When an item is clicked, all of the items expand/retract, which isn't what I want. I want each element to be independent.

I am connected to a database and basically want to display the data simply and be able to expand to see more information.

I've tried lots of different solutions, my current method is based off https://stackoverflow.com/a/18568997/1366033 What should I do about the id and href?

Any help would be greatly appreciated.

    foreach (var item in groupItem){

<div class="panel-group" id="accordion">
                        <div class="panel panel-default" id="panel1">
                            <div class="panel-heading">
                                <h4 class="panel-title">
                                    <a data-toggle="collapse" data-target="#collapseOne"
                                       href="#collapseOne">
                                       @Html.DisplayFor(modelItem => item.Name)
                                    </a>
                                </h4>

                            </div>
                            <div id="collapseOne" class="panel-collapse collapse in">
                                <div class="panel-body">@Html.DisplayFor(modelItem => item.IdNumber)
                                </div>
                            </div>
                        </div>

                    </div>

回答1:

Basically you are creating panel with loop and assigning the same id to all the panel-group and that's what causing the problem here! So you can try working as below and please note ids should be unique in DOM

@{int i=0;}
foreach (var item in groupItem)
{
       <div class="panel-group" id="accordion_@i">
              <div class="panel panel-default" id="panel_@i">
                     <div class="panel-heading">
                           <h4 class="panel-title">
                                 <a data-toggle="collapse" data-target="#collapseOne_@i" href="#collapseOne_@i">
                                       @Html.DisplayFor(modelItem => item.Name)
                                  </a>
                            </h4>
                      </div>
                      <div id="collapseOne_@i" class="panel-collapse collapse in">
                            <div class="panel-body">
                                 @Html.DisplayFor(modelItem => item.IdNumber)
                            </div>
                      </div>
              </div>
        </div>
        i++;
}