0

Please be gentle with me. Im not an expert.

Im posting a valid json (validated)

{
"Stats": [{
    "userName": "sadf",
    "id": "128",
    "score": "7"
}, {
    "userName": "fa",
    "id": "417",
    "score": "3"
}]
}



// POST api/comment
public void Post(List<Stat> Stats)
{
  string break= "Breakpoint here";
}


public class Stat
{
public string userName { get; set; }
public string id { get; set; }
public string score { get; set; }
}

No matter what, then I only get Stats == null in Post(List Stats)

This is the javascript code:

var stats = [{ "userName": "sadf" },
                { "userName": "fa" }];

        $.ajax({
            type: "POST",
            url: "http://localhost:56887/api/comment",
            data: JSON.stringify({ Stats: stats }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $.each(stats, function (k, v) {
                    alert(v.position);
                });
            },
            failure: function (errMsg) {
                alert(errMsg);

            }
        });

Any idea what's wrong?

5
  • 1
    You need to add the [FromBody] attribute to the method. See this answer stackoverflow.com/a/10986030/3279876 Commented Feb 13, 2017 at 14:41
  • I have already tried that without result. Commented Feb 13, 2017 at 14:43
  • 1
    In that case show your entire ajax post code. Commented Feb 13, 2017 at 14:44
  • @sami Just updated with javascript Commented Feb 13, 2017 at 14:49
  • 1
    Try changing data: JSON.stringify({ Stats: stats }) to data: JSON.stringify(stats) Commented Feb 13, 2017 at 14:54

1 Answer 1

1

You need a view model that will match this JSON structure:

public class MyViewModel
{
    public IList<Stat> Stats { get; set; }
}

that your controller action will take as parameter:

public void Post(MyViewModel model)
{
    // model.Stats will contain the desired collection here
}

If you want to bind directly to a List<Stat> then all you need to do is get rid of the Stats property that you artificially introduce when stringifying:

data: JSON.stringify(stats),

Also you might want to reconsider this parameter dataType: "json", especially if your controller action is void and doesn't return anything at the moment which obviously is wrong and it is not how controller action signatures are supposed to look like in ASP.NET Web API.

Sign up to request clarification or add additional context in comments.

1 Comment

data: JSON.stringify(stats), That did the trick. Thanks very much.

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.