2

I have a problem with posting converted json object to controller using antiforgerytoken. Passed argument questionnaireViewModel is null. I've tried to add to ajax:

contentType: "application/json",

or

headers: { '__RequestVerificationToken': token },

but nothing have changed. Could you help me?

@using (Html.BeginForm("PostQuestionnaire", "Home", FormMethod.Post, new { id = "__AjaxAntiForgeryQuestionnaireForm" }))
{
    @Html.AntiForgeryToken()
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PostQuestionnaire(QuestionnaireViewModel questionnaireViewModel)
    { ... }

$('#submitBtn').on('click', function () {

   var questionnaireVM = JSON.stringify({
    'questionnaireViewModel': {
        'QuestionnaireId': $('#QuestionnaireId').val(),
        'Revision': $('#Revision').val(),
        'IPAddress': '',        
    }
});

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

$.ajax({
    type: "POST",
    url: "./PostQuestionnaire",
    data: { 
            __RequestVerificationToken: token, 
            questionnaireVM 
        },
    success: function (result) {
        if (result.success) {
            console.log("success");

        } else {
            console.log("fail");
        }
    },
    error: function (request) {
            console.log("error");
    }
});
Milad Rashidi
  • 1,026
  • 4
  • 14
  • 33

1 Answers1

2

You don't need to stringify your data in POST methods, just make a json object:

let d = {
    'QuestionnaireId': $('#QuestionnaireId').val(),
    'Revision': $('#Revision').val(),
    'IPAddress': '',        
}

and replace the data part in your Ajax call with the following code:

data: { 
        __RequestVerificationToken: token, 
        questionnaireViewModel: d
    },
Elyas Esna
  • 458
  • 2
  • 15