Reputation: 53
I'm trying to generate an accordion dynamically using bootstrap and ASP.NET Core. The goal is to show all terms which belong to a certain category but the problem is that only the first two out of four categories are expanding/collapsing. I can see, that each card-header and card-body is available in the DOM. My code looks like this:
<div class="accordion" id="accordionExample">
@foreach (var category in this.Model.Categories)
{
var random = Guid.NewGuid();
<div class="card">
<div class="card-header" id="@random">
<h5 class="mb-0">
<button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#@category.Id" aria-expanded="false" aria-controls="@category.Id">
@category.CategoryName
</button>
</h5>
</div>
@foreach (var term in category.Terms)
{
<div id="@category.Id" class="collapse" aria-labelledby="@random" data-parent="#accordionExample">
<div class="card-body">
@term.GermanTranslation
</div>
</div>
}
</div>
}
</div>
Upvotes: 1
Views: 1013
Reputation: 21496
Your HTML has 2 problems:
.collapse
is not unique. You used @category.Id
within the terms loop..collapse
.
To me, generating the random number as card header's ID is unnecessary either. An accordion doesn't need an ID for each card header to work. You can use the category ID for the collapsible panels instead.
You said you would like to show all terms which belong to a certain category. Then the collapsible should be for each category, not for each term within a category. Your foreach
loop for category terms should be inside .card-body
.
I would suggest you give the following a try:
<div class="accordion" id="category-accordion">
@foreach (var category in this.Model.Categories)
{
<div class="card">
<div class="card-header">
<h5 class="mb-0">
<button class="btn btn-link collapsed" type="button"
data-toggle="collapse" data-target="#[email protected]">
@category.CategoryName
</button>
</h5>
</div>
<div id="[email protected]" class="collapse data-parent="#category-accordion">
<ul class="list-group list-group-flush">
@foreach (var term in category.Terms)
{
<li class="list-group-item">@term.GermanTranslation</li>
}
</ul>
</div>
</div>
}
</div>
This is generating collasible panel for each category, containing multiple translations.
Upvotes: 4