2013-03-26 63 views
2

我想要做的是將一個字符串/整數數組傳遞給mvc操作方法。 但數據總是返回爲空,我做錯了什麼?JQuery發佈數據到MVC操作方法?

MVC控制器

[HttpPost] 
public ActionResult MyAction(List<string> ids) 
{ 
    // do something with array 
    // But it's null 
     return View(); 
} 

JQuery的

$.post("/MyController/MyAction", JSON.stringify(ids), function() { alert("woohoo"); }, "application/json"); 

數據被派駐到行動結果

["156"] 

回答

3

嘗試:

... JSON.stringify({ ids : ids }), ... 

我很確定模型聯編程序不確定列表/數組是否應該被綁定。

考慮:

[HttpPost] 
public ActionResult MyAction(List<string> ids, List<string> blah) 
{ 
} 

如果JSON作爲只是值的數組,其參數做綁定太過去了? JSON可能比FORMS提交複雜得多,所以它也需要更多的定義。

例如,以下內容適用於以前的考慮。

{ 
    ids : ["asdf","asdf"], 
    blah : ["qwer", "qwer"] 
} 

更新來進行

爲了發送JSON正確下面Ajax調用需要:

$.ajax({ 
    type: "POST", 
    url: "/Home/Index", 
    data: JSON.stringify(ids), 
    contentType: "application/json; charset=utf-8" 
}); 

在後(您指定application/json)最後一個參數是什麼期待從服務器回來。默認情況下,$ .Post將執行表格編碼(application/x-www-form-urlencoded)contentType,該類型似乎被硬編碼到快捷方式中。要設置contentType,您必須使用長手版本$ .ajax。

+0

我已經嘗試過了,仍然會返回爲空{「ids」:[「156」]} – aryaxt 2013-03-26 21:12:03

+0

對不起,您還必須指定內容類型。更新答案。 – 2013-03-26 21:28:01

+0

我已經在我的代碼中,我開始並行(虛擬機),現在一切正常。太ba我不能刪除問題 – aryaxt 2013-03-26 21:44:44