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?

Lars Hansen
  • 155
  • 1
  • 2
  • 16

1 Answers1

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928