I have a HTML code:
<div >
<div >
@foreach(var post in Model)
{
<div >
<div >
<div >
<h2>@post.Title</h2>
<p>@post.Description</p>
<button type="button" data-bs-toggle="modal" data-bs-target="#wholePost" onclick="return showContent()">Show post...</button>
</div>
<div id="wholePost">
<div >
<div >
<div >
<h5 >@post.Title</h5>
<button type="button" data-bs-dismiss="modal"></button>
</div>
<div >
<p>@post.Content</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div >
col2
</div>
}
</div>
I want to make that to when I click on "Show Post" button modal window is open with corresponding content. Currently, if there is two blog posts clicking on button result in displaying content from the first post even If I click on button in the second blog post. I want to make that when I click on "Show post" in first blog post modal window opens with content from first blog post and when I click on button in the second blog post modal window open with content from second blog post.
I even don't understand where I should make this, in c# code or with javascript. Please provide me theory not a code if you could because I would like to guess on my own how to make this. Sorry in advance if there is post like that already and great thanks for your help.
CodePudding user response:
You could do it on JS but need to propagate HTML with some additional info
just some concept code for example:
<button onclick="showContent(@post.Id);">Show post...</button>
...
<div id="[email protected]">
JS file
function showContent(id){
$("#wholePost_" id).show();
}
There are probably some more ways to do it.
CodePudding user response:
The way bootstrap modals work is that the data-bs-target attribute in your button needs to have the same id as the modal so that's why it keeps opening the modal for your first element.
What you need to do is give each modal its separate id, so instead of #wholePost id for all of the modals it should be like #wholePost1, #wholePost2, ... .