2

I have the following type hierarchy for 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>
{
}

I instantiate in and return a ClientIndexModel from an ApiController as follows:

public ClientIndexModel Get()
{
    var model = new ClientIndexModel();
    return model;
}

If I inspect model with a breakpoint on the return model; line, the Items property is present, with a count of 0. Yet the JSON returned from this action only has the SelectListDictionary property and no Items property. Why could this be?

4

1 回答 1

2

您的Items财产有一个私人二传手。带有私有设置器的属性被故意从序列化中省略,因为序列化它们没有意义,因为它们永远不能反序列化,因为它们的值不能从外部修改。因此,您应该完全删除 setter(就像您对SelectListDictionary属性所做的那样),将其公开或使用一些能够使用私有 setter 序列化属性的自定义序列化程序编写自定义格式化程序。

于 2012-04-24T17:17:35.477 回答