[英]modal iteration in foreach loop using ajax
I got a problem with foreach loop.我遇到了 foreach 循环的问题。 What am i trying to do is get data (JsonResult) from action in controller.我想做的是从 controller 中的操作中获取数据(JsonResult)。 Get get songs for each album.获取每张专辑的歌曲。
public JsonResult SongListByAlbum(int albumID)
{
var songs = (from song in Song.GetSongList()
join album in Album.GetAlbumList()
on song.AlbumID equals album.AlbumID
where (albumID == album.AlbumID)
select song).ToList();
return Json(songs,JsonRequestBehavior.AllowGet);
}
Then put them into view, for album get list of songs and show them as modals There is my view:然后将它们放入视图中,对于专辑获取歌曲列表并将它们显示为模态有我的观点:
@foreach (var item in Model.Albums){
<button id="@item.AlbumID" type="button" class="btn btn-primary myModals" data-toggle="modal" data-target="#exampleModal-@item.AlbumID">
Show
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal-@item.AlbumID" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-@item.AlbumID" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel-@item.AlbumID">@item.AlbumName @item.Year, @item.BandName</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="parent" class="modal-body">
</div>
<div class="modal-footer">
<button id="closeModal"type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
}
And there is a script, where I get songs for each album.还有一个脚本,我可以在其中获取每张专辑的歌曲。
<script>
$(".myModals").on("click", function () {
var Id = $(this).attr('id');
alert(Id);
$.ajax({
type: "GET",
url: '@Url.RouteUrl(new{ action= "SongListByAlbum", controller="Default"})',
data: {albumID:Id},
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
for (var i in result) {
$('#parent').append('<p class="toRemove">' + result[i].SongName + '</p>');
}
},
error: function (response) {
alert('error');
}
});
});
</script>
The problem is: when i click on the first modal button everything is fine, i get what i want to.问题是:当我点击第一个模态按钮时,一切都很好,我得到了我想要的。 But when i click on the second one i got empty modal.但是当我点击第二个时,我得到了空模式。 Then when i click again on the first one i got data from previous click and penultimate.然后,当我再次单击第一个时,我从上一次单击和倒数第二个中获得了数据。 Image: enter image description here图片:在此处输入图片描述
To avoid multiple <div id="parent">
elements, you should probably assign the Id
the same way you do for the buttons.为避免出现多个<div id="parent">
元素,您应该按照与按钮相同的方式分配Id
。 Like <div id="parent-@item.AlbumID">
.像<div id="parent-@item.AlbumID">
。 Then in your ajax call reference the correct div.然后在您的 ajax 调用中引用正确的 div。 $('#parent-' + Id)
. $('#parent-' + Id)
。
Not sure if that is your only probably, but might get you closer.不确定这是否是你唯一的可能,但可能会让你更接近。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.