John John
John John

Reputation: 1

How to Pass my object ids to my action method using Ajax and jquery

I have the following field inside my asp.net mvc view:-

@foreach (var item in Model) {
    @Html.CheckBoxFor(model => item.CheckBoxSelection, new { @value = item.TMSServerID.ToString() })
}

and i wrote the following jquery to select the values for the CheckBox if selected :-

$('body').on("click", "#transferSelectedServers", function () {
    var boxData = [];
    $("input[name='CheckBoxSelection']:checked").each(function () {
        boxData.push($(this).val());
    });

    $.ajax({
        type: "POST",
        url: "@Url.Content("~/Server/DeleteSelected")",
        data: { ids: boxData.join(",") }
    })
});

and i have the following Action method:-

[HttpPost]
[ValidateAntiForgeryToken]
public string DeleteSelected(string ids)

but currently the values passed to my action method will be empty string.

Upvotes: 0

Views: 150

Answers (1)

heymega
heymega

Reputation: 9401

Your controller contains the ValidateAntiForgeryToken attribute. Since you arent passing the antiforgery token with your ajax request you're receiving an error.

If you check your response body you will probably see the error.

So you have two options

  1. Remove the ValidateAntiForgeryToken attribute
  2. Keep the ValidateAntiForgeryToken and pass the token over along with your ids

Update

Sending AntiForgeryToken using Ajax

Render the antiforgerytoken in your view by adding the following

@Html.AntiForgeryToken()

This will generate a hidden field like this...

<input type="hidden" value="SSjplL_6t1bxDmb8qTdHcqX5ScafLxw4kmFMzc1dJ7T4kuXfL3aiDWIrwEjk9JKsUV4TGUsENKbRTRJ0W2zYLeHjmtCg02TZQBDevWeRYEA1" name="__RequestVerificationToken">

All you need to do is pass over that value using __RequestVerificationToken as the object name.

So your ajax call will look something like this now...

  var token = $("input[name='__RequestVerificationToken']").val();

  $.ajax({
        type: "POST",
        url: "@Url.Content("~/Server/DeleteSelected")",
        data: { ids: boxData.join(","), __RequestVerificationToken: token }
    })

Hope this helps!

Upvotes: 1

Related Questions