asp.net-mvc - 为什么我的完整 View 模型没有被 ApiController 序列化?

标签 asp.net-mvc asp.net-mvc-4

我有以下 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/

相关文章:

.net - Razor 将枚举转换为 View 内的int

c# - jQuery 数据表插件 : Get json from server and displaying table

asp.net-mvc - asp.net MVC 3没有默认页面

asp.net-mvc - HttpClient传递多个简单参数

jquery - ASP.NET MVC SimpleMembership 登录因捆绑和缩小而失败

asp.net-mvc-4 - MVC 站点随机不返回 PartialView

c# - 在 MVC 中使用下拉菜单时出现错误?

javascript - 以不显眼的方式更好地组织和执行 JavaScript - 自执行匿名函数

c# - 使用下载弹出窗口自动从 URI 下载 xml 文件

javascript - 使用 jquery 从 displayfor 获取值