How are people handling AJAX posts to ActionMethod

2019-07-02 02:17发布

问题:

Seeing that the __RequestVerificationToken is not sent when using AJAX and ValidateAntiForgeryTokenAttribute is looking for the token in Request.Form, how are people dealing with this problem.

I ended up doing this.

$("#regmember-form").submit(function (e) {
    e.preventDefault();

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

    alert($(this).attr('action'));

    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: { __RequestVerificationToken: token }
    });

    return false;
});

Very similar to the accepted answer.

回答1:

I grab the input off the page and send it back with the form post. This assumes that you include it on the page in the first place.

 $('#somebutton').click( function() {
     var data = $('[name="__RequestVerificationToken"]').serialize();
     $.post('/foo/bar', data, function(result) {
        // ...
     });
 });