2012-06-05 15 views
3

我正在通過jquery ajax post將json數據發送給我的控制器操作。我的行爲中的IEnumerable一直爲空。模型聯編程序不會將json轉換爲IEnumerable <T>

是我的json錯誤或爲什麼模型聯編程序不能將json轉換爲IEnumerable?

public ActionResult Update(IEnumerable<Teststep> teststeps) 
{ 
    // 
} 

$.ajax({ 
      url: '@Url.Action("Update", "Teststep")', 
      type: 'POST', 
      data: [{ "errortext": "oh something bad happended.", "unitid": "10" }, { "errortext": "you got it man.", "unitid": "20"}], 
      success: function (response) { 
       debugger; 
       if (response.success) { 
        dlg.dialog("close"); 
        // Update UI 

       } 
       else { 
        // Reload the dialog with the form to show model/validation errors 
        dlg.html(response); 
       } 
      } 
     }); 

public class Teststep 
{ 

[HiddenInput(DisplayValue = false)] 
public int UnitId { get; set; }  

public string ErrorText { get; set; } 

// some other props removed for readability 

} 
+0

嘗試使用**一步步測試[] teststeps **作爲參數的方法 和序列化JSON: JSON.stringity([{ 「ERRORTEXT」:「哦,東西「unitid」:「10」},{「errortext」:「你得到它的人。」,「unitid」:「20」}]) – cycaHuH

+0

對不起,我沒有得到「嘗試使用Teststep []測試步驟爲...「你能重寫嗎? – Elisabeth

+0

'公共ActionResult更新(Teststep [] teststeps)' – cycaHuH

回答

1

爲了獲得集合(數組,ienumerables等),以通過ModelBinder的以操作方法正確傳遞,我一直到集傳統:在Ajax調用真正的選項:

$.ajax({ 
    url: '@Url.Action("Update", "Teststep")', 
    type: 'POST', 
    traditional: true, 
    ... 
+0

然後你做錯了事情。 – Elisabeth

+0

我對此表示懷疑。我只傳遞枚舉的基元,而不是複雜的類型。它使用'.serialize()'而不是'.stringify()'很好用。在你的情況下,stringify可能會更好,因爲看起來你想手動指定值而不是從表單輸入元素獲取它們。 – danludwig

+0

以及我只是試過這個:var data = ['11','22','33']; JSON.stringify(數據)和我的行動有一個IEnumerable 。我得到3的計數。所以它的工作。爲了測試目的,我手動指定它們是因爲我還不知道稍後將使用的數據網格,或者通過.val()從輸入元素獲取數據應該不起作用。 – Elisabeth

1

現在,它的工作原理!我在IEnumerable中獲得1項。這個問題是在搞砸了JSON ;-)

var data = { teststeps: [{ ErrorText: 'bla', UnitId: 10}] }; 
     $.ajax({ 
      url: '@Url.Action("Update", "Teststep")', 
      type: 'POST', 
      data: JSON.stringify(data), 
      dataType: 'json', 
      contentType: 'application/json'    
     }); 

[HttpPost] 
public ActionResult Update(IEnumerable<Teststep> teststeps) 
{ 

} 
相關問題