Reputation: 1
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
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
ValidateAntiForgeryToken
attribute ValidateAntiForgeryToken
and pass the token over along with your idsUpdate
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