ajax post .net web api参数为null

时间:2017-02-13 14:34:57

标签: asp.net json asp.net-web-api

请温柔地对待我。我不是专家。

我发布了一个有效的json(已验证)

{
"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; }
}

无论如何,我只能在Post(List Stats)中获得Stats == null

这是javascript代码:

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);

            }
        });

知道什么是错的吗?

1 个答案:

答案 0 :(得分:1)

您需要一个与此JSON结构匹配的视图模型:

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

您的控制器操作将作为参数:

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

如果你想直接绑定到List<Stat>,那么你需要做的就是摆脱字符串化时人为引入的Stats属性:

data: JSON.stringify(stats),

此外,您可能需要重新考虑此参数dataType: "json",,特别是如果您的控制器操作是void并且当前没有返回任何明显错误的内容并且不是控制器操作签名的假设看起来像在ASP.NET Web API中。