A ViewComponent in my ASP.NET Core 1.1
project on VS2015
has a confirm delete modal/dialog with Twitter bootstrap as shown below. But when a user clicks on the Delete
button to confirm a delete it does not trigger the jquery function shown below. The modal/dialog pops up fine but when I click on delete button with id= DeleteBtnID
inside the modal/dialog I would expect it to popup the `alert(‘Test’) but that is not happening. Question: What I may be missing? No errors are shown in Chrome’s Developer Tool.
View that calls ViewComponent:
@model MyProj.Models.TestModel
some html
....
....
<div id="DeleteBtnParentID">
@await Component.InvokeAsync("TestVC")
</div>
ViewComponent:
@model IEnumerable<MyProj.Models.TestModel>
<table>
@foreach (var item in Model)
{
<tr>
<td>
<a asp-action="TestAction">@item.Title</a>
</td>
<td>
<button type="button" class="btn btn-info btn-xs" data-toggle="modal" data-target="#myModal">Delete</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header btn-warning" style="font-weight:bold;color:white;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h5 class="modal-title modal-sm">Delete Warning</h5>
</div>
<div class="modal-body">
<p>Click 'Delete' to <strong>parmenently</strong> delete this record. Click 'Cancel' to cancel your action.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" id="DeleteBtnID" value="@item.id" data-dismiss="modal">Delete</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</td>
</tr>
}
</table>
@section scripts
{
<script>
$(document).ready(function () {
$('#DeleteBtnParentID').on('click', '#DeleteBtnID', function (event) {
alert('Test');
});
});
</script>
}
Snapshot of the page source when I use Chrome’s developer toot [You can click on the image for a larger view]:
2
Answers
you are trying to find DeleteBtnID on the first level under DeleteBtnParentID.
try to use find instead, it will search all level that are under DeleteBtnParentID
ANSWER UPDATE
From comment:
A way to solve this point can be:
Updated snippet:
From your code:
The IDs must be unique. So, I suggest you to insert in each table cell only the button and move outside the modal, i.e.:
So, the event will be attached to the unique modal button.
The snippet: