给定以下客户端代码片段:
var vm = {
Input : "Label: Value",
Rules : [
{ Name : "RemoveString",
Params : [
"Label: "
]
}
]
};
$.post("/API/ApplyRule", vm, function(data) { });
以及服务器端的以下 ViewModel:
[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: " }
}
}
}
我在这里做错了什么?为什么它没有正确绑定规则数组?
您是否需要创建自己的自定义模型绑定器才能正确绑定它?如果是这样,怎么做?