2012-06-12 85 views
1

考慮下面的客戶端代碼片段:如何正確模型子對象到ASP.NET MVC視圖模型綁定JSON?

var vm = { 
    Input : "Label: Value", 
    Rules : [ 
    { Name : "RemoveString", 
     Params : [ 
     "Label: " 
     ] 
    } 
    ] 
}; 

$.post("/API/ApplyRule", vm, function(data) { }); 

而在服務器端以下視圖模型:

[Serializable] 
public class ApplyRuleRequestViewModel 
{ 
    public string Input { get; set; } 
    public List<RuleViewModel> Rules { get; set; } 
} 

[Serializable] 
public class RuleViewModel 
{ 
    public string Name { get; set; } 
    public List<string> Params { get; set; } 
} 

而下面的控制器代碼:

public class APIController : Controller 
{ 
    [HttpPost] 
    public ActionResult ApplyRule(ApplyRuleRequestViewModel model) 
    { 
     //Problem here... model is not fully deserialized into the ViewModel object. 
     return View(); 
    } 
} 

我有一個問題試圖序列化客戶端ViewModel的規則部分。當在上面的// Problem ...上方的控制器行上調試代碼時,我發現頂級對象屬性產生了它,而不是子對象。所以,我得到的是這樣的:

var vm = new ApplyRuleRequestViewModel { 
    Input = "Label: Value", 
    Rules = new List<RuleViewModel> { 
    new RuleViewModel { Name = null, Parameters = null } 
    } 
} 

我期待這樣的:

var vm = new ApplyRuleRequestViewModel { 
    Input = "Label: Value", 
    Rules = new List<RuleViewModel> { 
    new RuleViewModel { 
     Name = "RemoveString", 
     Parameters = new List<string> { "Label: " } 
    } 
    } 
} 

我在做什麼錯在這裏? 爲什麼它沒有正確地綁定規則數組?

你需要創建正確綁定這個自己的自定義模型綁定?如果是這樣,怎麼樣?

回答

1

您可以將您的留言JSON。

var vm = { 
    Input : "Label: Value", 
    Rules : [ 
    { Name : "RemoveString", 
     Params : [ 
     "Label: " 
     ] 
    } 
    ] 
}; 

$.postJson("/API/ApplyRule", vm, function(data) { }); // See below for definition of `.postJson`. 

最後一個參數json將設置接受標頭以指示需要JSON。默認模型聯編程序應自動與內置的JsonValueProviderFactory進行交互,以正確讀取結構化消息。

編輯錯過了一些東西。您需要設置contentType,所以.post因爲它代表可能無法正常工作。

這裏是發佈JSON的助手方法(不僅僅是POSTING和接收 json,因爲post會做)。

$.postJson = function(url, data, success) { 
    $.ajax({ 
      url: url, 
      type: 'POST', 
      dataType: 'json', 
      data: JSON.stringify(data), 
      contentType: 'application/json; charset=utf-8', 
      success: success 
     }); 
} 
+0

好吧會嘗試... –

+0

謝謝,那工作:) –