当尝试通过Ajax发布向我的MVC控制器提交JSON有效负载时,我看到了非常奇怪的行为。
这是代码:
[HttpPost]
public ActionResult ResetEligibility(EmployeeEligibilityFilter filter) { ... }
public class EmployeeEligibilityFilter
{
public List<int> Selection { get; set; }
public bool SelectionInverted { get; set; }
public int? BenACACalendarCycleId { get; set; }
...
}
有效负载:
{"BenACACalendarCycleId":2,"SelectionInverted":false,"Selection":[680,698,875]}
现在,如果我提供的
Selection
列表少于3个元素,则Selection
属性突然开始在服务器端以null
的形式出现。{"BenACACalendarCycleId":2,"SelectionInverted":false,"Selection":[680,875]}
其他属性继续正确反序列化。
我们在这里迷路了...
更多研究:将模型属性从
List<int>
更改为List<object>
可以使事情正常进行。尽管存储在对象列表中的元素仍然是System.Int32
。我什至尝试像这样并排使用:
public class EmployeeEligibilityFilter
{
public int? BenACACalendarCycleId { get; set; }
public bool SelectionInverted { get; set; }
public List<int> Selection { get; set; }
public List<object> _Selection { get; set; }
}
并在两个中发送完全相同的数组:
{"BenACACalendarCycleId":2,"SelectionInverted":false,"Selection":[663],"_Selection":[663]}
最终结果仍然相同。
Selection
出现为空,但_Selection
已正确反序列化。巫毒魔法...
最佳答案
试试吧:
[TestMethod]
public void GetAAA() {
var json = "{'BenACACalendarCycleId':2,'SelectionInverted':false,'Selection':[663],'_Selection':[663]}";
EmployeeEligibilityFilter obj = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<EmployeeEligibilityFilter>(json);
}
public class EmployeeEligibilityFilter
{
public int? BenACACalendarCycleId { get; set; }
public bool SelectionInverted { get; set; }
public List<int> Selection { get; set; }
public List<object> _Selection { get; set; }
}