asp.net-mvc – MVC不是json序列化实现IEnumerable的模型上的其
我不知道为什么我现在才第一次注意到这种行为.希望确认这是否是设计行为,或者我是否遗漏了某些东西.
假设我有一个实现IEnumerable< T>的viewmodel,并提供其他属性.例如: public class MyResultsViewModel : IEnumerable<MyResultViewModel> { public IEnumerable<MyResultViewModel> Results { get; set; } public string SomeAdditionalProperty { get; set; } public IEnumerator<MyResultViewModel> GetEnumerator() { return Results.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator; } } 假设我还有一个控制器,它将此模型作为json返回.例如: public ActionResult MyResults() { var entities = PrivateMethodToGetEntities(); var models = Mapper.Map<MyResultsViewModel>(entities); models.SomeAdditionalProperty = "I want this in the JSON too"; return Json(models,JsonRequestBehavior.AllowGet); // models now contains a populated Results as well as the add'l string prop } 当我从客户端上的JSON请求返回结果时,它总是以数组形式返回.例如: $.get('/Path/To/MyResults') .success(function (results) { alert(results.SomeAdditionalProperty); // this alerts 'undefined' alert(results.length); // this alerts the size / count of Results alert(results[0]); // this alerts object // inspecting results here shows that it is a pure array,with no add'l props }); 在我重构以使viewmodel不实现IEnumerable< T>之前,我想得到一些确认,这是设计的,应该是预期的.我想这是有道理的,因为必须扩展javascript数组对象的原型以适应其他属性. 更新: 我对viewmodel进行了以下更改,以避免命名内部可枚举结果: public class MyResultsViewModel : IEnumerable<MyResultViewModel> { public IEnumerable<MyResultViewModel> NotNamedResults { get; set; } public string SomeAdditionalProperty { get; set; } public IEnumerator<MyResultViewModel> GetEnumerator() { return NotNamedResults.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator; } } 通过此更改,行为仍然存在. alert(JSON.stringify(results))为我的枚举MyResultViewModel集合生成正常的数组语法:
在控制器操作返回JsonResult并调用jquery成功函数之间,似乎仍然丢失了附加属性. 解决方法
对于实现IEnumerable的类,JavascriptSerializer仅序列化枚举项.它调用GetEnumerator()来获取要序列化的数据,忽略任何其他属性.这就是List< T>的Count属性的原因.不是序列化的,也不是任何其他财产.
原因是这种结构不能用json格式表示.要包含序列化程序必须创建散列对象而不是数组的其他属性,但严格来说,散列对象不是集合. (例外的是键/值对类,如Dictionary,它被序列化为哈希对象.但规则代表 – 只有枚举的字典条目被序列化). 但是为什么要创建一个直接实现IEnumerable的类来序列化为json而不是这样做? public class MyResultsViewModel { public IEnumerable<MyModel> Models{ get; set; } public String SomeAdditionalData { get; set; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |