Hanady Hanady - 2 years ago 120
jQuery Question

Error in sending parameters to controller through @Url.Action in JQuery

I am working on an

project and I was trying to send some parameters to my controller in

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) {
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?

The HTML button is placed inside a

@foreach (var item in Model)
@Html.DisplayFor(modelItem => item.TeamName)
@Html.DisplayFor(modelItem => item.TeamInits)
@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>

Answer Source

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; 
        var id = $(this).data('id');

        //Rest of the code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download