# AJAX Data Binding

## Content

AJAX helps you to load data in the background and display it on the webpage, without reloading the complete webpage. It provides a smoother user experience while you are working with paging, sorting or filtering features in FlexGrid. This topic describes how to bind a FlexGrid at client side using an AJAX call.
This topic comprises the following steps:

* [Step 1: Create a Model](/componentone/docs/mvc/online-mvc-core/WorkingwithControls/FlexGrid/WorkwithFlexGrid/DataBindingFlexGrid/AJAX-Data-Binding#step-1-create-a-model)
* [Step 2: Add a Controller Action](/componentone/docs/mvc/online-mvc-core/WorkingwithControls/FlexGrid/WorkwithFlexGrid/DataBindingFlexGrid/AJAX-Data-Binding#step-2-add-a-controller-action)
* [Step 3: Add FlexGrid to View](/componentone/docs/mvc/online-mvc-core/WorkingwithControls/FlexGrid/WorkwithFlexGrid/DataBindingFlexGrid/AJAX-Data-Binding#step-3-add-flexgrid-to-view)
* [Step 4: Make an AJAX call using JavaScript](/componentone/docs/mvc/online-mvc-core/WorkingwithControls/FlexGrid/WorkwithFlexGrid/DataBindingFlexGrid/AJAX-Data-Binding#step-4-make-an-ajax-call-using-javascript)
* [Step 5: Build and Run the Project](/componentone/docs/mvc/online-mvc-core/WorkingwithControls/FlexGrid/WorkwithFlexGrid/DataBindingFlexGrid/AJAX-Data-Binding#step5)

The following image shows how the FlexGrid appears after completing the steps above:
![C1Web FlexGrid DataBinding - AJAXBinding usage](https://cdn.mescius.io/document-site-files/images/9b6a6cfe-b8e8-42e9-8a04-da6cb7762977/images/flexgridajaxbinding.png)

### Step 1: Create a Model

2. 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](/componentone/docs/mvc/online-mvc-core/Adding-Controls).
3. 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.

    ```csharp
    using System;
    using System.Collections.Generic;
    using System.Linq;
    namespace AjaxDataBinding.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<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" };
            /// <p>DOC-SUMMARY-TAG-OPEN</p>
            /// Get the data.
            /// <p>DOC-SUMMARY-TAG-CLOSE</p>
            /// <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; }
        }
    }
    ```

### Step 2: Add a Controller Action

1. Open the `HomeController.cs` from the Controllers folder.
2. Add the following code to return JSON data.

    ```csharp
    [HttpPost]
            public JsonResult GetData()
            {
                List<Sale> saleList = Sale.GetData(10).ToList<Sale>();
                return Json(saleList);
            }
    ```

### Step 3: 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 declare a FlexGrid control. The code below declares different columns and properties of the FlexGrid, but does not bind data to the control.

    ```html
    <c1-flex-grid id="fg" height="500px" is-read-only="true" auto-clipboard="true"
                  auto-generate-columns="false" allow-add-new="false"
                  allow-sorting="true" selection-mode="@((SelectionMode.Cell))">
    <c1-flex-grid-column name="ID" width="0.4*"></c1-flex-grid-column>
    <c1-flex-grid-column name="Product" header="Product" width="*"></c1-flex-grid-column>
    <c1-flex-grid-column name="Country" header="Country" width="*"></c1-flex-grid-column>
    <c1-flex-grid-column name="Amount" header="Amount" width="*"></c1-flex-grid-column>
    </c1-flex-grid>
    ```

### Step 4: Make an AJAX call using JavaScript

We'll bind data to the control on the client side using JavaScript to make an AJAX call to the Action created in the **HomeController.cs** file. When we bind the grid at client-side in the Load function below, instead of assigning the result data of AJAX call to FlexGrid **itemSource** property, we should update the sourceCollection of FlexGrid's **collectionView** at client-side to retain the server-side features of collectionView. We have also added a code check for any errors in date values of JSON data.

1. In the **Solution Explorer**, click the **Views** folder.
2. Open the `Index.html` file inside the **Home** folder and copy the following JavaScript code.

    ```html
    <script type="text/javascript">
       function parseDate(strDate) {
            var date = strDate.match(/\d+/g);
            return new Date(parseInt(date));
        }
        function Load() {
            $.ajax({
                type: "POST",
                url: "/Home/GetData",
                dataType: "json",
                success: function (result) {                
                    var flex = wijmo.Control.getControl("#fg"),
                        cv = flex.collectionView;
                    //flex.itemsSource = result;
                    try {
                        cv._isFillingData = true;
                        cv.deferUpdate(function () {
                            cv.sourceCollection.clear();
                            result.forEach(function (item) {
                                item.Start = parseDate(item.Start);
                                item.End = parseDate(item.End);
                                cv.sourceCollection.push(item);
                            });
                        })
                    } finally {
                        cv._isFillingData = false;
                    }
                },
                error: function (err) {
                }
            });
        }
    </script>
    ```
3. Add the following code to call the above script on a button click.

    ```html
    <input type="button" id="btload" value="Get Data" onclick="Load()" />
    ```

### Step 5: Build and Run the Project

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