Why Can't .NET Core handle JQuery Ajax Post ?

Johnny Olsen 21 Reputation points

I have added a simple JQuery Ajax call using POST.
The call is using JSON and the parameters I send are turned into nulls when received in the Controller (MVC)
The same code (except a few things on the controller part are slightly different to meet the specifications regarding JSON) works when I run .NET Framework. But fails on .NET Core. Here is the client code:
var pdata = JSON.stringify({ name:"Johnny Olsen", age:63, SSN:"200757-0409" });
type: "POST",
url: "home/personInfoPost",
contentType: "application/json",
data: pdata,
success: function(res){
``And server-side code is
like this: [HttpPost]
public string personInfoPost([FromBody] string name, int age, string SSN)
var str = name + ", " + age.ToString() + ", " + SSN;
return str + " are Received ok...";

Hope you can explain why I have this problem. /Johnny Olsen

A set of technologies in the .NET Framework for building web applications and XML web services.
4,360 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 50,916 Reputation points

    Model binding in ASP.NET Core is different than ASP.NET as discussed here. Even in ASP.NET your controller doesn't seem like it should work properly.

    The binder attempts to match parameters to the received data via the URL, form values, etc. Any that match are assigned to parameters. The FromBody attribute tells the binder to look at the body of the request to match the data. Hence in your case it would look in the body of the request. But the assumption here is that it is a model so the parameter name itself is irrelevant. Since string doesn't have any properties it wouldn't try to match anything. The other 2 parameters are not specified as FromBody, because only 1 parameter supports this, and therefore would never be bound. AFAIK this wouldn't even have worked in ASP.NET but honestly I never would have tried it anyway.

    The correct approach to storing data in the body and mapping multiple values to it is to define a model type with the fields inside. Then use the model as a parameter with the FromBody attribute.

       public class PersonInfoModel  
          public string Name { get; set; }  
          public int Age { get; set; }  
          public string SSN { get; set; }  
       public string personInfoPost ( [FromBody] PersonInfoModel model )  
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Raja Bhushan 1 Reputation point

    I have created a sample to handle this scenario and posted on GitHub https://github.com/rajabb/MvcCore6JsonUploadSample . Hope that should solve your issue.

    0 comments No comments