I am working on an MVC
project and I was trying to send some parameters to my controller in JQuery
using @Url.Action
.
HTML code:
<button class="btn btn-white btn-sm demo1" data-id='@item.TeamID'>Delete</button>
JQuery Code:
$(document).ready(function () {
$('.demo1').click(function (event) {
swal({
title: "Are you sure?",
text: "You will not be able to recover this team!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function () {
var data = event.data;
var id = data.id;
var url = '@Url.Action("Delete", "Teams", new { id = "__param__" })';
window.location.href = url.replace('__param__', encodeURIComponent(id));
swal("Deleted!", "Your team has been deleted.", "success");
});
});
});
However, the Delete method in the Teams controller is not being triggered. Am I missing something?
UPDATE:
The HTML button is placed inside a foreach
loop:
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.TeamName)
</td>
<td>
@Html.DisplayFor(modelItem => item.TeamInits)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.TeamID }, new { @class = "btn btn-white btn-sm" })
<button class="btn btn-white btn-sm demo1" data-id='@item.TeamID'>Delete</button>
</td>
</tr>
}
Use HTMLElement.dataset property or .data()
to read the custom data-*
prefixed attribute value.
$(document).ready(function () {
$('.demo1').click(function (event) {
var id = this.dataset.id;
//OR
var id = $(this).data('id');
//Rest of the code
swal();
});
});