Working with Controls / FlexGrid / Work with FlexGrid / Unbound FlexGrid / Unbound FlexGrid using AJAX Call
Unbound FlexGrid using AJAX Call

FlexGrid when in bound mode, the data in the grid is populated automatically from a particular data source. However, in case of an unbound FlexGrid, you need to add/remove the grid columns and rows using different method provided in the API.

This topic describes how to populate data in an unbound FlexGrid at client side using AJAX.

The following image shows how you can populate data in an unbound FlexGrid at client side using AJAX. The example uses Sale.cs model added in the QuickStart section.

UnboundFlexGrid

Step 1: Configure MVC Application

In Visual Studio, create a new MVC application using ASP.NET Core Web Application (Model-View-Controller) template. For more information on how to create an MVC Core application, see Using Visual Studio Template topic.

Back to Top

Step 2: Create a Model

  1. Add a new class to the folder Models (For example: Sale.cs). For more information on how to add a new model, see Adding Controls.
  2. Replace the following code in the Sale.cs model. We are using Sale class to represent sales order data in the database. Each instance of Sale object will correspond to a record in the FlexGrid control.
    C#
    Copy Code
    public class Sale
      {
      public int ID { get; set; }
      public DateTime Start { get; set; }
      public DateTime End { get; set; }
      public string Country { get; set; }
      public string Product { get; set; }
      public string Color { get; set; }
      public double Amount { get; set; }
      public double Amount2 { get; set; }
      public double Discount { get; set; }
      public bool Active { get; set; }
      
      public MonthData[] Trends { get; set; }
      public int Rank { get; set; }
      
    private static List <string> COUNTRIES = new List<string> { "US", "UK", "Canada", "Japan", "China", "France", "German", "Italy", "Korea", "Australia" };
    private static List<string> PRODUCTS = new List<string> { "Widget", "Gadget", "Doohickey" };
    
            /// Get the data.
            public static IEnumerable<Sale> GetData(int total)
            {
                var colors = new[] { "Black", "White", "Red", "Green", "Blue" };
                var rand = new Random(0);
                var dt = DateTime.Now;
                var list = Enumerable.Range(0, total).Select(i =>
                {
                    var country = COUNTRIES[rand.Next(0, COUNTRIES.Count - 1)];
                    var product = PRODUCTS[rand.Next(0, PRODUCTS.Count - 1)];
                    var color = colors[rand.Next(0, colors.Length - 1)];
                    var startDate = new DateTime(dt.Year, i % 12 + 1, 25);
                    var endDate = new DateTime(dt.Year, i % 12 + 1, 25, i % 24, i % 60, i % 60);
    
                    return new Sale
                    {
                        ID = i + 1,
                        Start = startDate,
                        End = endDate,
                        Country = country,
                        Product = product,
                        Color = color,
                        Amount = Math.Round(rand.NextDouble() * 10000 - 5000, 2),
                        Amount2 = Math.Round(rand.NextDouble() * 10000 - 5000, 2),
                        Discount = Math.Round(rand.NextDouble() / 4, 2),
                        Active = (i % 4 == 0),
                        Trends = Enumerable.Range(0, 12).Select(x => new MonthData                     { Month = x + 1, Data = rand.Next(0, 100) }).ToArray(),
                        Rank = rand.Next(1, 6)
                    };
                });
                return list;
            }
            public static List<string> GetCountries()
            {
                var countries = new List<string>();
                countries.AddRange(COUNTRIES);
                return countries;
            }
            public static List<string> GetProducts()
            {
                List<string> products = new List<string>();
                products.AddRange(PRODUCTS);
                return products;
            }
        }
        public class MonthData
        {
            public int Month { get; set; }
            public double Data { get; set; }
        }
        public class BasicSale
        {
            public int Sale { get; set; }
            public DateTime Date { get; set; }
    
            public BasicSale(int sale, DateTime date)
            {
                Sale = sale;
                Date = date;
            }
            public static List<BasicSale> GetBasicSales()
            {
                List<BasicSale> list = new List<BasicSale>();
                int[] sales = {
                96, 19, 54, 83, 15, 56, 36, 4, 29, 93,
                38, 71, 50, 77, 69, 13, 79, 57, 29, 62,
                4, 27, 66, 96, 65, 12, 52, 3, 61, 48, 50,
                70, 39, 33, 25, 49, 69, 46, 44, 40, 35,
                72, 64, 10, 66, 63, 78, 19, 96, 26};
                for (int i = 0; i < sales.Length; i++)
                {
                    list.Add(new BasicSale(sales[i], new DateTime(2014, i / 31 + 1, i % 31 + 1)));
                }
                return list;
            }
        }                 
    
Back to Top

Step 3: Add a Controller Action

  1. Open the HomeController.cs from the Controllers folder and add the following references.
    C#
    Copy Code
    using C1.Web.Mvc;
    using C1.Web.Mvc.Serialization;
    using FlexGridIntro.Models;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    
  2. Replace the method Index() with the following method.
    C#
    Copy Code
    private static List<Sale> Sales = Sale.GetData(50).ToList<Sale>();
    
     public IActionResult Index()
        {   
            return View();
        }
     public JsonResult GetJsonData()
        {
            return Json(Sales);
        }
    
Back to Top

Step 4: Add FlexGrid to View and Generate Data in FlexGrid using AJAX

  1. Open the Index.html from View/Home folder.
  2. Replace the content of this file with the following code to configure a FlexGrid control. The code below declares different columns and properties of the FlexGrid, but does not bind data to the control.
    CSHTML
    Copy Code
    <script>
        $.ajax({
            type: "POST",
            url: "/Home/GetJsonData",
            dataType: "json",
            success: function (data) {
                var fg = wijmo.Control.getControl("#flexgrid"); //get FlexGrid reference
                fg.rows.clear();  //clear any existing rows from FlexGrid
                var j = 0
                for (var i in data) {
                    var obj = [data[i].product, data[i].country, data[i].amount];
                    var row = new wijmo.grid.Row();  // add row to FlexGrid
                    fg.rows.push(row);
                    for (var col = 0; col <= fg.columns.length - 1; col++) {
                        fg.setCellData(j, col, obj[col]);  //add data to FlexGrid Cell.
                    }
                    j++;
                }
            },
            error: function (err) {
                alert("err");
            }
        });
    </script>
    
    <c1-flex-grid auto-generate-columns="false" key-action-tab="Cycle" height="500px" id="flexgrid">
        <c1-flex-grid-column name="Product" header="Product"></c1-flex-grid-column>
        <c1-flex-grid-column name="Country" header="Country"></c1-flex-grid-column>
        <c1-flex-grid-column name="Amount" header="Amount"></c1-flex-grid-column>
    </c1-flex-grid>
    
Back to Top

Step 5: Build and Run the Project

  1. Click Build | Build Solution to build the project.
  2. Press F5 to run the project to load and display the data in the FlexGrid.

Back to Top

See Also