0

I am using an ASP.NET Core 3.0 MVC application in which I make the following jQuery Ajax call:

return $.ajax({
    type: type,
    url: '/' + controller + '/' + action,
    data: jsonData,
    timeout: timeout,
    contentType: "application/json; charset=utf-8",
    success: function (returnedData) {
        successFunc(returnedData);
    },
    error: function (errMsg) {
        errorFunc(errMsg);
    }
});

passing it the data object

{
  input1: 'random',
  input2: '1',
  input3: '1',
},

But it always passes null arguments through:

Null arguments from Ajax call

I have also tried adding addnewtonsoftjson() in startup but it doesn't seem to change anything.

A similar question here, doesn't really have an answer: .Net Core 3.0 AJAX POST Body Always Null

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

0

I think your problem is kinda relative to the HTTP method/type you are using and the contentType you are passing to the backend.

I've found a great summary of contentType here

If you don't wanna dive too deep into this you could change your contentType into application/x-www-form-urlencoded; charset=UTF-8 should resolve your problem

coposaja
  • 61
  • 4
  • I used contentType: "application/json; charset=utf-8", changed the type to GET and removed the JSON.stringify and this now works. Seemingly i don't understand AJAX. – user11917447 May 04 '20 at 22:10
0

So keep the c# code as you have shown in your question. In you js call:

var data = JSON.stringify({ 
                 'input1': ‘inputvalue’,
                 'input2':’inputvalue’,
                 ‘input3’: ‘inputval’
               });

$.ajax({
        type: "POST",
        url: same as you have in the question
        data: data,

        contentType: 'application/json',

success: function (returnedData) {
        successFunc(returnedData);
    },
    error: function (errMsg) {
        errorFunc(errMsg);
    }

    });
YankTHEcode
  • 634
  • 4
  • 8
0

The error seems to com from defining the content type.

   return $.ajax({
        type: type,

        url: '/' + controller + '/' + action,
        data: jsonData,

        success: function (returnedData) {
            successFunc(returnedData);
        },
        error: function (errMsg) {
            errorFunc(errMsg);
        }
    });

has no contentType defined and passes through to the action in the controller correctly.