ASP.NET MVC Controls | ComponentOne
Working with Controls / FlexGrid / Work with FlexGrid / Unbound FlexGrid / Using AJAX Call
In This Topic
    Using AJAX Call
    In This Topic

    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 data from the server will be stored in a dictionary, which is serialized to JSON before sending it to the client.

    To accomplish this, follow these steps:

    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

    Configure MVC Application

    1. In Visual Studio, create a new MVC application using C1 ASP.NET MVC 5 Web Application template. For more information on how to create an MVC application, see Using ComponentOne Template topic.
    2. In ComponentOne ASP.NET MVC Application Wizard, check Enable Client IntelliSense and Add TS options.
    Back to Top

    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" };
              /// <summary>
              /// Get the data.
              /// </summary>
              /// <param name="total"></param>
              /// <returns></returns>
              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

    Add a Controller Action

    1. Open the HomeController.cs from the Controllers folder.
    2. Add the following code to create a dictionary with a unique key and employee object in the GetDictionaryData function. Also, you need to serialize the dictionary data to JSON using JavaScriptSerializer in GetData function.
      C#
      Copy Code
      public ActionResult Index()
        {
        return View();     
        }
        [HttpPost]
        public JsonResult GetData()
        {
        // return Json(JsonConvert.SerializeObject(GetDictionaryData()));
        JavaScriptSerializer sz = new JavaScriptSerializer();
        string str = sz.Serialize(GetDictionaryData());
        return Json(str);
        }     
        private Dictionary<string,Sale> GetDictionaryData()
        {
        var dict = new Dictionary<string, Sale>();
        var sales = Sale.GetData(10);
        for(int i=0; i<=sales.Count()-1;i++)
        {
        dict.Add(i.ToString(), sales.ElementAt(i));
        }
        return dict;
        }
      
    Back to Top

    Add FlexGrid to View

    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.
      Razor
      Copy Code
      @using <ApplicationName>.Models
      <script src="~/Scripts/app.js"></script>
        
      @* Loads from a dictionary *@
      <input type="button" onclick="Load()" value="Ajax Load" />
        
      @(Html.C1().FlexGrid().Id("fg").Height(400).AutoGenerateColumns(false).AllowAddNew(false)
        .SelectionMode(C1.Web.Mvc.Grid.SelectionMode.Cell)
        .Columns( col => {
        col.Add(cb => cb.Name("Product").Header("Product"));
        col.Add(cb => cb.Name("Country").Header("Country"));
        col.Add(cb => cb.Name("Amount").Header("Amount"));
      }))
      
    Back to Top

    Generate Data in FlexGrid using AJAX

    1. In the Solution Explorer, open the app.js file from the Scripts folder.
    2. In app.js file, add the following script to populate data at the client side in the FlexGrid control.
      app.js
      Copy Code
      /// <reference path="typings/c1.mvc.core.lib.d.ts" />     
      function Load() {
          $.ajax({
              type: "POST",
              url: "/Home/GetData",
              dataType: "json",
              success: function (result) {
                  var fg = <wijmo.grid.FlexGrid>wijmo.Control.getControl("#fg"); //get FlexGrid reference
                  var data = JSON.parse(result);  //parse the server Dictionary data to JSON array
                  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");
              }
          });       
      
    Back to Top

    Build and Run the Project

    1. Click Build | Build Solution to build the project.
    2. Press F5 to run the project and then, click AJAX Load button to load and display the data in the FlexGrid.

    Back to Top

    See Also