2017-02-13 47 views
0

請溫和我一下。我不是專家。ajax post .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; } 
} 

不管是什麼,然後我只得到統計==在帖子(列表統計)空

這是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

您需要將[FromBody]屬性添加到該方法。看到這個答案http://stackoverflow.com/a/10986030/3279876 – Sami

+0

我已經嘗試過,沒有結果。 –

+1

在這種情況下,顯示您的整個ajax郵政編碼。 – Sami

回答

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。

+0

數據:JSON.stringify(統計),該訣竅。非常感謝。 –