• asp.net mvc 对象和集合序列化


    private List<Model.Organization.Organization> GetOrganiztions()
    {
    var organizations = new List<Model.Organization.Organization>();

    organizations.Add(new Model.Organization.Organization
    {
    Id = "1",
    Name = "一汽",
    });

    organizations.Add(new Model.Organization.Organization
    {
    Id = "2",
    Name = "红旗",
    ParentId = "1"
    });
    organizations.Add(new Model.Organization.Organization
    {
    Id = "3",
    Name = "奔腾",
    ParentId = "1"
    });
    organizations.Add(new Model.Organization.Organization 
    {
    Id="4",
    Name="奔腾B70",
    ParentId="3"
    });
    return organizations;
    }

    private void AttachChildren(TreeModel tree, List<Model.Organization.Organization> organizations)
    {
    if (Equals(tree, null))
    {
    return;
    }

    var organizationsTmp = organizations.Where(p => !string.IsNullOrEmpty(p.ParentId) && p.ParentId.Equals(tree.id)).ToList();
    foreach (Model.Organization.Organization node in organizationsTmp)
    {
    var t = new TreeModel() { 
    id=node.Id,
    text=node.Name
    };
    tree.children.Add(t);
    this.AttachChildren(t, organizations);
    }
    }

    public IList<TreeModel> GetTree()
    {
    var organizations = this.GetOrganiztions();
    var rootNode = organizations.Find(p => string.IsNullOrEmpty(p.ParentId));
    var tree = new TreeModel()
    {
    id = rootNode.Id,
    text = rootNode.Name
    };

    this.AttachChildren(tree, organizations);
    return new List<TreeModel>() { tree };
    }

    如果GetTree返回的是集合,则Controler调用GetTree序列化为json以后为:

    [{"id":"1","text":"一汽","children":[{"id":"2","text":"红旗","children":[]},{"id":"3","text":"奔腾","children":[{"id":"4","text":"奔腾B70","children":[]}]}]}]

    如果GetTree返回的是对象,则Controler调用GetTree序列化为json以后为:

    {"id":"1","text":"一汽","children":[{"id":"2","text":"红旗","children":[]},{"id":"3","text":"奔腾","children":[{"id":"4","text":"奔腾B70","children":[]}]}]}

    在asp.net mvc中前端我们可能会经常用到json数组,我们可以考虑使用Json(集合)的方式,这样一来可以不用在前端再去处理
  • 相关阅读:
    Perl的运算符号字符
    windows xp 使用远程桌面时的关机/重新启动方法
    抵御TCP的洪水
    远程桌面连接中的常见问题 连接上就断开
    批量kill mysql进程
    Linux如何查看硬盘型号和缓存
    Apache Rewrite 规则详解
    nginx 内置变量大全
    大数据量分页存储过程效率测试附代码
    ASP.Net 更新页面输出缓存的几种方法(包括用户控件,iframe,页面缓存等)
  • 原文地址:https://www.cnblogs.com/bygrace/p/3794776.html
Copyright © 2020-2023  润新知