0

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>
 }
Hanady
  • 779
  • 2
  • 15
  • 38

2 Answers2

1

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();
    });
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • `var id = $(this).data('id');` worked for me, but the id is returned as null to the controller. Please note that the html button is placed inside a foreach loop. Check updated question. – Hanady May 24 '16 at 09:37
0

I usually Try the below code trick. When anything goes wrong like this.

Add the below code in you Global.asax.cs file and Put debugger inside the method, so that it Will be triggered when ever exception occurs.

protected void Application_Error(object sender, EventArgs e)
{ 
    Exception exception = Server.GetLastError();
    string ex = exception.Message; // Here you will get to know what is going wrong
}

The exception message or the stack trace will provide the enough information details to fix the errors.

Even though if its request from Jquery / Razor Html page errors, you will have enough info.

Hope this helps!!!

RajeshKdev
  • 6,365
  • 6
  • 58
  • 80