Skip to main content Skip to footer

Populate Data to an Unbound FlexGrid, Part II: Convert C# Dictionary Data to JSON in an Unbound MVC Grid

In this second article of a two-part series on unbound FlexGrids, we'll look at populating data per cell to an unbound FlexGrid via data from AJAX call. In addition, the data from the server will be in a Dictionary, which is serialized to JSON before sending to client.

Download ComponentOne Studio

In this example, we have a server-side Sales class as our model. We wish to populate data from three columns: Product, Country and Amount. Since FlexGrid is unbound, the needs to be available at client side.

Let's start by setting up the project.

  1. In Visual Studio, create a new project using "C1 ASP.NET MVC 5 Web Application" template.
  2. Enable client side TypeScript IntelliSense through the project wizard. (Using TypeScript for writing client side code is recommended although not necessary.)

Add Model to the Project

We 'll use a Sales class that returns a list of sales objects. Add the following Sales class to the Model folder:


  using System;  
  using System.Collections.Generic;  
  using System.Linq;  
  namespace UnboundFlexGrid.Models  
  {  
  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</p>  
<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;  
        }  
    }  
}  

Controller: Provide Data to View

  1. Open the HomeController.CS.
  2. Here, create a dictionary with a unique key and employee object in the GetDictionaryData function.
  3. Serialize this dictionary data to JSON using JavaScriptSerializer (OR using JSON convert) in GetData function.
  4. Send it to the client.

  public class HomeController : Controller  

  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;  
  }  

View

  1. Open the Index.cshtml file under Views > Home folder
  2. Delete all content
  3. Configure the FlexGrid by declaring columns and out-of-box properties as below:

  @using UnboundFlexGrid.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"));  

  }))  

Populating FlexGrid with Data

Open the App.ts file added to the project by the C1 Project template wizard, and add the following script to populate data to FlexGrid:


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");  
        }  
    });  

Here's what happens in this script:

  1. Get data from an AJAX call; this data is in dictionary format.
  2. Use JSON parse to get a JSON array of the data.
  3. Use the client-side reference of FlexGrid
  4. Loop through the number of items in the array to ascertain the number of rows to be added to FlexGrid.
  5. Extract the values of required three columns in an array from the JSON array
  6. Uuse setCellData method of FlexGrid to add data to FlexGrid cells.
  7. Add a reference of above app.ts file to the _Layout.cshtml or Index.cshtml file.
  8. Run the application and click on "AJAX Load" button to populate the FlexGrid.

To read about populating data to an unbound FlexGrid using CollectionView, read the first blog in our series.

MESCIUS inc.

comments powered by Disqus