Using Bootstrap Modal with a foreach loop

前端 未结 1 957
广开言路
广开言路 2021-01-15 10:03

I have a foreach loop which loops through my documents from a database, it only pulls in the IMAGES then I have a 4 images per row on my page, I would like to click one it o

相关标签:
1条回答
  • 2021-01-15 10:47

    In your particular solution you are using the same modal snippet for each item in your Model.DocumentList. For example:

    <a class="thumbnail" data-toggle="modal)" data-target="#myModal" title="@item.FileDescription"> @Html.DocumentUrl(item.FileUrl, false)</a>
    

    If always toggling the modal with an id of myModal. The first modal the page renders is winning out whenever you click the DocumentUrl. You are essentially creating 4 of the same modal with the only differentiator being the Url and Item, and because of this you're experiencing the strange behavior.

    To accomplish what you're trying to accomplish (at least in the way that you are approaching the problem), you could utilize a unique id on each modal by concatenating the id with a value off of your item. For example:

    <a class="thumbnail" data-toggle="modal)" data-target="#myModal-@(item.id)" title="@item.FileDescription"> @Html.DocumentUrl(item.FileUrl, false)</a>
    
    <div class="modal fade" id="myModal-@(item.id)" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><!-- modal body etc --></div>
    

    By using the id off of the Model you will generate a unique HTML modal for each item in your Model.Document list and a unique data-target to match. This would accomplish what you're trying to do by using 4 seperate modals.

    A small alternative suggestion if you feel like refactoring this later. You could always load a single modal on the page and use JavaScript to modify the modal's body. This would clean up the HTML by using only a single modal rather than 4 seperate modal snippets. You would load an empty modal in your page for example and use the loop to generate the links with the proper data-atteributes. This way your code is DRY and your HTML is clean.

    Happy Coding!

    0 讨论(0)
提交回复
热议问题