ASP.NET MVC Controls | ComponentOne
Working with Controls / FlexGrid / Work with FlexGrid / TreeGrid / Binding to XML
In This Topic
    Binding to XML
    In This Topic

    You can use XML documents as a hierarchical data source for the FlexGrid control and display the data as tree as shown in the following image.

    MVC FlexGrid TreeGrid binding with XML

    The following example shows how you can use XML documents as a hierarchical data source for the FlexGrid control. It uses XElement.Load method to load the XML element from file that contains the content of the XML document and loops through the XML element to build an array with "category" items, each with a "products" array. The array is used as an ItemsSource and the ChildItemsPath property is used to show the products for each category as a tree. The example uses ProductCategories.xml file as a data source.

    Controller code

    TreeGridXMLController.cshtml
    Copy Code
    public ActionResult TreeGridXML()
    {
        return View();
    }
    
    public ActionResult GetProductsByCategory([C1JsonRequest] CollectionViewRequest<TCategory> requestData)
    {
        var items = new List<TCategory>();
        var xml = XElement.Load(System.Web.HttpContext.Current.Server.MapPath("~/Content/data/ProductCategories.xml"));
        // get categories
        var categories = xml.Elements("category");
        foreach (var cg in categories)
        {
            items.Add(new TCategory
            {
                Id = Convert.ToInt32(cg.Attribute("id").Value),
                Name = cg.Attribute("name").Value,
                Products = new List<TProduct>()
            });
            // get products in this category
            var products = cg.Elements("product");
            foreach (var p in products)
            {
                items[items.Count - 1].Products.Add(new TProduct
                {
                    Id = Convert.ToInt32(p.Attribute("id").Value),
                    Name = p.Attribute("name").Value,
                    Price = Convert.ToDouble(p.Attribute("price").Value)
                });
            }
        }
        return this.C1Json(CollectionViewHelper.Read(requestData, items));
    }
    
    public class TCategory
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<TProduct> Products { get; set; }
    }
    
    public class TProduct
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }
    

    View code

    TreeGridXML.razor
    Copy Code
    @(Html.C1().FlexGrid().Id("grid").Width(700).Height(500)
        .Bind("GetProductsByCategory")
        .ChildItemsPath("Products")
        .AutoGenerateColumns(false)
        .Columns(columns =>
        {
            columns.Add().Binding("Name").Width("*");
            columns.Add().Binding("Id").Width("80");
            columns.Add().Binding("Price").Width("80");
        })
    )