【问题标题】:ajax post .net web api parameter is nullajax post .net web api 参数为空
【发布时间】:2017-02-13 14:34:56
【问题描述】:

请对我温柔一点。我不是专家。

我发布了一个有效的 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);

            }
        });

知道有什么问题吗?

【问题讨论】:

  • 您需要在方法中添加 [FromBody] 属性。看到这个答案stackoverflow.com/a/10986030/3279876
  • 我已经试过了,没有结果。
  • 在这种情况下显示您的整个 ajax 邮政编码。
  • @sami 刚刚用 javascript 更新
  • 尝试将数据:JSON.stringify({ Stats: stats }) 更改为数据:JSON.stringify(stats)

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


【解决方案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&lt;Stat&gt;,那么你需要做的就是去掉你在字符串化时人为引入的Stats属性:

data: JSON.stringify(stats),

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

【讨论】:

  • data: JSON.stringify(stats),这成功了。非常感谢。
猜你喜欢
  • 2017-08-28
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 2017-08-03
  • 2013-05-31
  • 2017-08-09
  • 2018-01-24
  • 2013-07-31
相关资源
最近更新 更多