ASP.NET Core MVC Controls | ComponentOne
Working with Controls / CollectionView / Work with CollectionView / Client- Side Operations / Sorting
In This Topic
    Sorting
    In This Topic

    The CollectionView class supports sorting through the ICollectionView interface, similar to .NET. To enable sorting, add one or more sortDescriptions objects to the CollectionView.sortDescriptions property. The result can be obtained from the CollectionView.items property.

    SortDescription objects are flexible, allowing you to sort data based on value in ascending or descending order. In the sample below, you can sort the collection based on the corresponding field value chosen in the first list. You can also specify the sorting order in the second list.

    Make sure that the DisableServerRead property of ItemSource is set to True if filtering, paging, sorting is to be performed on data available at client side only.

    The example uses C1NWind datasource, which was configured in the application in the Quick Start:

    The following code example demonstrates how to apply sorting in FlexGrid through CollectionView.

    In Code

    SortingController.cs

    C#
    Copy Code
    private C1NWindEntities db = new C1NWindEntities();
    
    public ActionResult Index()
    {
        return View(db);
    }
    

    Sorting.cshtml

    HTML
    Copy Code
    <div class="row-fluid well row">
        <div class="col-md-8">
            <select id="sortingFieldNameList" class="form-control"></select>
        </div>
        <div class="col-md-4">
            <select id="sortingOrderList" class="form-control">
                <option value="true" selected="selected">Ascending</option>
                <option value="false">Descending</option>
            </select>
        </div>
    </div>
    <c1-flex-grid auto-generate-columns="false" id="sortingGrid"
                   is-read-only="true" allow-sorting="false">
        <c1-items-source source-collection="@Model"></c1-items-source>
        <c1-flex-grid-column binding="CustomerID"></c1-flex-grid-column>
        <c1-flex-grid-column binding="CompanyName"></c1-flex-grid-column>
        <c1-flex-grid-column binding="ContactName"></c1-flex-grid-column>
        <c1-flex-grid-column binding="City" format="c"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Country" format="p0"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Phone"></c1-flex-grid-column>
    </c1-flex-grid>
    
    Script
    Copy Code
    <script>
        function getNames() {
            return ['CustomerID', 'CompanyName', 'ContactName', 'City', 'Country', 'Phone'];
        };
    
        $(document).ready(function () {
            //Sorting
            sortingGrid = wijmo.Control.getControl('#sortingGrid');
            cvSorting = sortingGrid.itemsSource;
            sortingFieldNameList = document.getElementById('sortingFieldNameList');
            sortingOrderList = document.getElementById('sortingOrderList');
            // initialize the list items for field names and orders.
            sortingFieldNameList.innerHTML += '<option value="" selected="selected">Please choose the field you want to sort by...</option>';
            for (var i = 0; i < sortingNames.length; i++) {
                sortingFieldNameList.innerHTML += '<option value="' + sortingNames[i] + '">' + sortingNames[i] + '</option>';
            }
    
            // track the list change in order to udpate the sortDescriptions property.
            sortingFieldNameList.addEventListener('change', sortGrid);
            sortingOrderList.addEventListener('change', sortGrid);
    
            //Sorting
            // create collectionview, grid, the jQuery elements, the field name list.
            var cvSorting = null,
                sortingGrid = null,
                sortingFieldNameList = null,
                sortingOrderList = null,
                sortingNames = getNames();
    
            function sortGrid() {
                var fieldName = sortingFieldNameList.value,
                    ascending = sortingOrderList.value,
                    sd, sdNew;
    
                if (!fieldName) {
                    return;
                }
    
                ascending = ascending === 'true';
                sd = cvSorting.sortDescriptions;
                sdNew = new wijmo.collections.SortDescription(fieldName, ascending);
    
                // remove any old sort descriptors and add the new one
                sd.splice(0, sd.length, sdNew);
            };
    
        })
    </script>
    

    Sort Null Values

    CollectionView allows you to sort null values using the SortNulls property, which determines how the null values are sorted. The SortNulls property accepts values from the CollectionViewSortNulls enumeration that lets you choose the sorting order from the following values:

    The following example illustrates how to sort null values so that they appear first on the sorted collection. This example uses a class named Sale which contains sales data for various countries.

    Sorting null values in a way that they appear first on the sorted collection

    Sale.cs

    Sale.cs
    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; }
    
        /// <summary>
        /// Get the data.
        /// </summary>
        /// <param name="total"></param>
        /// <returns></returns>
        public static IEnumerable<Sale> GetData(int total)
        {
            var countries = new[] { "US", "UK", "Canada", "Japan", "China", "France", "German", "Italy", "Korea", "Australia" };
            var products = new[] { "Widget", "Gadget", "Doohickey" };
            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.Length - 1)];
                var product = products[rand.Next(0, products.Length - 1)];
                var color = colors[rand.Next(0, colors.Length - 1)];
                var date = new DateTime(dt.Year, i % 12 + 1, 25, i % 24, i % 60, i % 60);
    
                return new Sale
                {
                    ID = i + 1,
                    Start = date,
                    End = date,
                    Country = country,
                    Product = product,
                    Color = color,
                    Amount = rand.NextDouble() * 10000 - 5000,
                    Amount2 = rand.NextDouble() * 10000 - 5000,
                    Discount = rand.NextDouble() / 4,
                    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 class MonthData
    {
        public int Month { get; set; }
        public double Data { get; set; }
    }
    

    Controller Code

    SortingController.cs
    Copy Code
    public IActionResult Index()
    {
        var model = Sale.GetData(10).ToList();
        var nullObj = new Sale { };
        model.Add(nullObj);
        return View(model);
    }
    

    View Code

    Index.cshtml
    Copy Code
    @using C1.Web.Mvc.Grid
    @using CVSorting_Core.Models
    
    @model IEnumerable<Sale>
    
    <c1-items-source id="CVService" read-action-url="@Url.Action("Index")" sort-nulls="Natural">
    </c1-items-source>
    
    <c1-flex-grid id="FlexGridCV" items-source-id="CVService" auto-generate-columns="false" class="grid">
        <c1-flex-grid-column binding="ID"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Start" format="MMM d yy"></c1-flex-grid-column>
        <c1-flex-grid-column binding="End" format="HH:mm"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Country"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Product"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Color"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Amount" format="c"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Amount2" format="c"></c1-flex-grid-column>
        <c1-flex-grid-column binding="Active"></c1-flex-grid-column>
    </c1-flex-grid>