简体   繁体   中英

Cannot sort table headers by ascending or descending

By default the View displays a sorted table which is great but cannot Sort the table columns by clicking on the table headers in ascending or descending order. The header column arrows goes up and down on clicks but the data stays the same. I am using jQuery jTable and sorting is enabled by default.

Is is possible to do this by using a jQuery?

Here's my code for your inspection:

View:

$(document).ready(function () {
    $('#TopPlayedInVenueContainer1').jtable({

        title: 'Top Tracks Played Records',
        paging: true,
        pageSize: 100,
        sorting: true,
        defaultSorting: 'Date ASC',

        actions: {
            listAction: '@Url.Action("TopPlayedInVenueList1")'

        },
        fields: {
            TrackID: {
                title: 'Track ID',
                key: true,
                create: false,
                edit: false,
                resize: false,
                tooltip: 'Track Name',
                sorting: true //This column is not sortable!
            },
            Date: {
                title: 'Date',
                type: 'date',
                displayFormat: 'dd - mm - yy',
                tooltip: 'DD - MM - YY',
                list: true,
                sorting: true //This column is not sortable!
            },
            TrackName: {
                title: 'Track Name',
                key: true,
                create: false,
                edit: false,
                resize: false,
                tooltip: 'Track Name',
                sorting: true //This column is not sortable!
            },
            ArtistName: {
                title: 'Artist Name',
                key: true,
                create: false,
                edit: false,
                resize: false,
                tooltip: 'Track Name',
                sorting: true //This column is not sortable!
            },
            Times: {
                title: 'Times',
                tooltip: 'Artist Name',
                sorting: false //This column is not sortable!
            }
        }
    });

    // All
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    var todayDate = new Date();
    var endDate = todayDate.getDate() + '/' + (todayDate.getMonth() + 1) + '/' + (todayDate.getFullYear() + 100);
    var d = new Date();
    var st = d.setDate(todayDate.getDate() - 111365);
    var startDate = d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear();
    $('#allrecordsstart').val(startDate);
    $('#allrecordsend').val(endDate);
    $('#TopPlayedInVenueContainer1').jtable('load', {
        StartDate: startDate,
        EndDate: endDate
    });

    $('#allrecords').click(function (e) {
        e.preventDefault();
        var startDate = $('#allrecordsstart').val();
        var endDate = $('#allrecordsend').val();

        $('#TopPlayedInVenueContainer1').show(0).delay(0).fadeIn(1000).jtable('load', {
            StartDate: startDate,
            EndDate: endDate

        });
    });

Controller: Edit for @CHash_Mile.. thanks a lot :) here's the code: EDIT: 15/04/2014

[HttpPost]
    public JsonResult TopPlayedInVenueList1(string StartDate = "", string EndDate = "", int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
    {
        try
        {

            if (Request.IsAuthenticated == true)
            {
                string Path = @"C:\\5Newwithdate-1k.xls";
                OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
                OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
                con.Close();
                System.Data.DataTable data = new System.Data.DataTable();
                da.Fill(data);

                List<TopPlayed> daa = new List<TopPlayed>();

                foreach (DataRow p in data.Rows)
                {
                    TopPlayed top = new TopPlayed()
                    {
                        TrackID = Convert.ToInt32(p.Field<double>("TrackID")),
                        Date = p.Field<DateTime>("DateTimes"),
                        TrackName = p.Field<string>("TrackName"),
                        ArtistName = p.Field<string>("ArtistName"),
                        Times = Convert.ToInt32(p.Field<double>("Times"))
                    };

                    daa.Add(top);
                }

                var listOrder = daa.Where(i => i.Date >= Convert.ToDateTime(StartDate) && i.Date <= Convert.ToDateTime(EndDate)).ToList();

                if (jtStartIndex + 150 > listOrder.ToList().Count)
                {
                    int val = listOrder.ToList().Count - jtStartIndex;
                    jtPageSize = val;
                }

                var newlist = listOrder.OrderByDescending(i => i.Times).ToList().GetRange(jtStartIndex, jtPageSize);

                if (string.IsNullOrEmpty(jtSorting)) { jtSorting = "Date ASC"; }

                SortDirection sortDirection = jtSorting.ToLower().Contains("desc") ? SortDirection.DESC : SortDirection.ASC;
                string sortExpression = sortDirection == SortDirection.DESC ? jtSorting.ToLower().Replace(" desc", "") : jtSorting.ToLower().Contains(" asc") ? jtSorting.ToLower().Replace(" desc", "") : jtSorting;

                if (sortDirection == SortDirection.ASC)
                {
                 newlist = newlist.OrderBy(item => GetPropertyValue(item, sortExpression)).ToList();
                }
                else
                {
                 newlist = newlist.OrderByDescending(item => GetPropertyValue(item, sortExpression)).ToList();
                }

                return Json(new { Result = "OK", Records = newlist, TotalRecordCount = listOrder.ToList().Count });
            }
            return Json(new { Result = "ERROR" });
        }
        catch (Exception ex)
        {
            return Json(new { Result = "ERROR", Message = ex.Message });
        }
    }

Debugged using Step Over line by line and seems to be this line of the code is the culprit:

newlist = newlist.OrderBy(item => GetPropertyValue(item, sortExpression)).ToList();

Because after this line I get error message on the View in browser:

Object reference not set to an instance of an object.

Images: Edit for @CHash_Mile.. thanks a lot man :) screenshots of the debug:

sortExpression ---------- URL 在此处输入图片说明

newList ---------- URL 在此处输入图片说明

I'm sorry for taking your time soo much and really appreciate in what you're doing for me!

Check this Sorting using Jtable example

I see you are not using variable jtSorting for sorting. this gives property with which sorting needs to be done. Try with below code after loading newlist.

        SortDirection sortDirection = jtSorting.ToLower().Contains("desc") ? SortDirection.DESC : SortDirection.ASC;
    string sortExpression = sortDirection == SortDirection.DESC ? jtSorting.ToLower().Replace(" desc", "") : jtSorting.ToLower().Contains(" asc") ? jtSorting.ToLower().Replace(" desc", "") : jtSorting;

    if (sortDirection == SortDirection.ASC)
            {
                newlist = newlist.OrderBy(item => GetPropertyValue(item, sortExpression))).ToList();
            }
            else
            {
                newlist = newlist.OrderByDescending(item => GetPropertyValue(item, sortExpression))).ToList();
            } 

Add below method -

    public static object GetPropertyValue(object obj, string propertyName)
    {
        return obj == null ? null : obj.GetType().GetProperty(propertyName).GetValue(obj, null);
    }

Add below enum inside your class -

internal enum SortDirection { ASC, DESC }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM