Arianit Arianit - 5 months ago 21
jQuery Question

jQuery popup doesn't work well with Asp.Net MVC

I am trying to make a confirm to delete dialog with a popup in a Asp.Net Core (mvc) project.
The code is like this:

<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>

<td>
@Html.DisplayFor(modelItem => item.RepFile)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ID">Details</a> |
<!--<a asp-action="Delete" asp-route-id="@item.ID">Delete</a>-->
<input type="button" id="deleteReport"value="Delete"/>
</td>
}
<div id="dialog">
<h3>Are you sure you want to delete this report?</h3>
</div>


and the jquery:



var dialogDiv = $("#dialog");

$("#deleteReport").click(function () {
dialogDiv.dialog("open");
});

dialogDiv.dialog({
title:"Confirm Delete",
autoOpen:false,
modal: true,
draggable: false,
resizable: false,
closeOnEscape: false,
buttons: {
"Delete": function () {
dialogDiv.dialog("close");
},
"Cancel": function () {
dialogDiv.dialog("close");
}
}
});

</script>`


The problem is: the popup doesn't work, BUT it works only for just one specific record in the (db) table. Why, how can I fix this unknown problem? (the popup function is not finished yet, but that is not my concern for now, but any help how to make it functional, to delete records from the database would be most welcome)

Answer

It looks like there are a couple issues.

  1. You're not closing your table row. Add a </tr> before you close the @foreach block.

  2. You're using an ID as the selector, and the ID is in a loop, so it will create multiple items in your page with the same ID.

Why this is an issue:

The HTML spec states that IDs must be unique on the page. Since that is the case, jQuery will only find the first item with the ID and then not even look for anything else, so the event will only be bound to that one dom element. With the event bound to only one element, it will only fired when you click that one element.

The fix:

First, change the id to a class. This will allow you to apply the event to all dom elements with that class.

Second, change your jQuery to:

$(".deleteReport").click(function () {
    dialogDiv.dialog("open");
 });

To delete the row, you need to leverage $(this) in the method to select the buttons parent <tr>, which you should probably add a class to as well to make selecting it more specific. See an example of removing a table row using jquery on click here.

Comments