1

I came through old Q&A like jQuery posts null instead of JSON to ASP.NET Web API (on this site),
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/ or
https://weblog.west-wind.com/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods...
I tried all the hints and solutions, but I still have no values in my controller.
Here is my code:

Client HTML file :

var coup = { Token: token, MotPropose: RecupMot() };
var coupJSON = JSON.stringify(coup);

$.ajax({
            type: 'POST',
            url: urlJeu,
            dataType: 'json', 
            data: coupJSON,
            success: function (reponseJSON) {
                 /* CODE HERE */
            },
        });

Which sends correctly the following JSON (says Fiddle):

{"Token":103,"MotPropose":"ravoi"}

(BTW, I'm concerned about the missing " around the int 103, no?)

Server C# controller and object:

public object Post([FromBody]CoupMeliMelo coup)
{
    return Ok(jeu.JouerLeCoup(coup));
}

public class CoupMeliMelo : ICoup
{
    public string MotPropose { get; set; }
    public int Token { get; set; }
}

Then, when the JSON comes to the controller, the object coup is created, but MotPropose is null and Token is 0.

I'm stuck! Thanks for your help.

6
  • Could you ensure RecupMot() function return string value? Commented Jun 26, 2015 at 14:12
  • Yes, actually it returns "ravoi". Commented Jun 26, 2015 at 14:16
  • Try adding contentType: "application/json; charset=utf-8", to your ajax call. Commented Jun 26, 2015 at 14:19
  • Is this a Web API controller or a MVC Controller? Commented Jun 26, 2015 at 14:46
  • It is a Web API controller. Commented Jun 29, 2015 at 8:51

1 Answer 1

0

First off, there's no reason to call stringify. Just post the object. Second, send the content as application/json.

var coup = { Token: token, MotPropose: RecupMot() };

$.ajax({
        type: 'POST',
        url: urlJeu,
        dataType: 'json', 
        contentType: "application/json",
        data: coup,
        success: function (reponseJSON) {
             /* CODE HERE */
        },
    });

Finally, the [FromBody] attribute is not applicable to ASP.NET MVC, only WebApi. You don't need it.

public object Post(CoupMeliMelo coup)
{
    return Ok(jeu.JouerLeCoup(coup));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, it is WebApi, hence I kept [FromBody] Then I removed stringify, then added the ContentType, but no success... (Sorry for the delay: I jumped to VS 2015, with some trouble...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.