Pickels
Pickels

Reputation: 34690

Asp.net Mvc: Jquery post array + anti forgery token

how do I post an array to an action on my controler with the anti forgery token.

This is my Jquery postdata:

var postData = { '__RequestVerificationToken': $('input[name=__RequestVerificationToken]').val(), 'productIds': IDs };

this is my Jquery post:

$.post("MyProducts/DeleteProduct" , postData, function(data) { });

This is my action:

public void DeleteProduct(List<int> productIds)
    {
        foreach (int i in productIds)
        {
            _repository.DeleteProduct(i, null);
        }        
    }

I also use an object to store my anti forgery token and I wonder how I can use that with the postdata.

This is the token object:

var token = { '__RequestVerificationToken': $('input[name=__RequestVerificationToken]').val() };

Kind regards

Upvotes: 4

Views: 3761

Answers (2)

Dave Archer
Dave Archer

Reputation: 3060

var ids = [1,2];

var data = {
__RequestVerificationToken : token,
productIds : ids
};

$.post(url, data, function() ...

where token is the var you mentioned

Upvotes: 3

Dmytrii Nagirniak
Dmytrii Nagirniak

Reputation: 24118

Assuming you have all your product IDs in the HTML it would be much easier to use jqueryForm plugin:

$("form").ajaxSubmit({url: "MyProducts/DeleteProduct", success: function(response) {
  // Handle the response
}})

Upvotes: 1

Related Questions