2012-06-12 88 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

谢谢,那工作:) –