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: " }
}
}
}
我在做什麼錯在這裏? 爲什麼它沒有正確地綁定規則數組?
你需要創建正確綁定這個自己的自定義模型綁定?如果是這樣,怎麼樣?
好吧會嘗試... –
謝謝,那工作:) –