我有以下 ClientIndexModel
类型层次结构:
public class ViewModel
{
public virtual IDictionary<string, SelectList> SelectListDictionary
{
get
{
var props = GetType().GetProperties().Where(p => p.PropertyType == typeof(SelectList));
return props.ToDictionary(prop => prop.Name, prop => (SelectList)prop.GetValue(this, null));
}
}
}
public class IndexModel<TIndexItem, TEntity> : ViewModel where TIndexItem : ViewModel where TEntity : new()
{
public List<TIndexItem> Items { get; private set; }
}
public class ClientIndexModel: IndexModel<ClientIndexItem, Client>
{
}
我实例化并从 ApiController 返回一个 ClientIndexModel
,如下所示:
public ClientIndexModel Get()
{
var model = new ClientIndexModel();
return model;
}
如果我在 return model;
行上使用断点检查 model
,则 Items
属性存在,且计数为 0。然而,从此操作返回的 JSON 仅具有 SelectListDictionary
属性,没有 Items
属性。为什么会这样?
最佳答案
您的 Items
属性有一个私有(private) setter 。具有私有(private) setter 的属性被故意从序列化中省略,因为序列化它们是没有意义的,因为它们永远无法反序列化回来,因为它们的值无法从外部修改。因此,您应该完全删除 setter (就像您对 SelectListDictionary 属性所做的那样),将其公开或使用某些能够使用私有(private) setter 序列化属性的自定义序列化程序编写自定义格式化程序。
关于asp.net-mvc - 为什么我的完整 View 模型没有被 ApiController 序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10302664/