0

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 enter image description here

newList ---------- URL enter image description here

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

pv619
  • 409
  • 11
  • 29
  • check this [http://stackoverflow.com/questions/10321038/jtable-clickable-column-sorting-sorting-sorts-content-of-cells-but-doesnt-upd] – CHash11 Apr 11 '14 at 13:40
  • thanks for the link but that is for Java's jTable and I have issue with C# jQuery's jTable. – pv619 Apr 11 '14 at 13:42

1 Answers1

0

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 }

CHash11
  • 746
  • 4
  • 14
  • 31
  • thanks @CHash_Mile - I am getting data from a `local excel` file so will this work? Because I had a go at it like two weeks ago and it didn't work for me, unless I didn't did it properly. – pv619 Apr 14 '14 at 06:36
  • I see you are not using variable for sorting. Add this line – CHash11 Apr 14 '14 at 08:52
  • @CHash_Milk - thanks :) what line do you want me to add? – pv619 Apr 14 '14 at 08:57
  • thanks alot for this and I see what you mean.. thanks for making it clear as I am kinda new to C# @CHash_Mike - I have tried your code but it gives me the following error "Does not exist in the current context" for these two `sortDirection` and `ReflectionHelper`. I have updated my code above for your inspection. thanks again a million :) – pv619 Apr 14 '14 at 09:16
  • Updated my answer to load sortDirection and sortExpression. Check the updated code... Don't forget to mark as answer if it helps you to solve your problem. – CHash11 Apr 14 '14 at 09:53
  • thanks for that @CHash_Mike.. everything complied now properly :) on the `View` I get the following error. `Object reference not set to an instance of an object.` I will surely mark it as an answer and will +1 rep and everything I can do.. Also buy u a drink :) I have been stuck with this for over two weeks. I have updated my code above for your inspection and thanks again a million :) – pv619 Apr 14 '14 at 09:58
  • Keep debugger and check on which object is it giving object reference not set.. just check whats the value populated in "jtSorting". I sense there might be an issue. – CHash11 Apr 14 '14 at 10:02
  • I am confused about this line `internal enum SortDirection { ASC, DESC }`, where in the class do you want me to include? thanks again and sorry for taking your time soo much. Appreciate all your help :) – pv619 Apr 14 '14 at 10:09
  • I had to change `SortDirection.ASC` and `SortDirection.DESC` to `SortDirection.Ascending` and `SortDirection.Descending` and had to add `@using System.Web.Helpers;` for `SortDirection`.. is that right? Thanks again man hope we get this to work almost there.. – pv619 Apr 14 '14 at 10:17
  • you could add that above method GetPropertyValue.. Yes you can even use System.Web.Helpers.SortDirection, no issues with that.. Add null check before using jtSorting or add this if (string.isNullOrEmpty(jtSorting)) { jtSorting = "Date ASC"; } – CHash11 Apr 14 '14 at 10:24
  • thanks for that I added `internal enum SortDirection { ASC, DESC }` above the `GetPropertyValue class` and removed `using System.Web.Helpers` and re-added `SortDirection.ASC` and `SortDirection.DESC` just to keep your code clean. By using the `if (string.isNullOrEmpty(jtSorting)) { jtSorting = "Date ASC"; }` above jtSorting is gives me this error `string does not contain a definition for isNullorEmpty`. How can I tackle this? think we are almost there and sorry for taking too long as you can tell I'm new with all this.. and thanks again for everything :) – pv619 Apr 14 '14 at 10:36
  • rename it to "IsNullOrEmpty" – CHash11 Apr 14 '14 at 11:52
  • Wow that resolved the error but on the View I still get the same error `Object reference not set to an instance of an object` and I have updated my code above in the post.. I am soooo sorry for taking this long maybe you can help me one last time? thanks again and really appreciate it :) – pv619 Apr 14 '14 at 12:05
  • debug whats causing "Object reference not set to an instance of an object " – CHash11 Apr 14 '14 at 12:30
  • I am getting that error on the `View` as in after it's complied. No errors on the Visual Studio, it's on the browser that I'm getting.. thanks again Chash_Mike :) – pv619 Apr 14 '14 at 12:33
  • YEs but while debuggin it must give it for particular line.. you would have to cehck that line. "Object ref" errors are easy to solve.. – CHash11 Apr 14 '14 at 13:10
  • I hear you man but I tested it several times and it's not giving me any particular line - how can i check that? Let me tell u this that you have been a massive help! just can't get my head around this thing.. seems soo impossible :( – pv619 Apr 14 '14 at 13:39
  • Man I'm hope that I'm right - Did a `Debug` line by line using `Step Over` and found out to be this line is the culprit. `newlist = newlist.OrderBy(item => GetPropertyValue(item, sortExpression)).ToList();` because passed this line I get the `Object reference not set to an instance of an object.` error.. Hope it's right :) I have updated my full code in the post above and thanks.. hope you help out last time please :) – pv619 Apr 14 '14 at 14:21
  • check what's value of sortExpression and also check whether any of newlist item is null – CHash11 Apr 14 '14 at 14:40
  • Man how can I thank you? You just showed me how to debug very effectively in VS.. `sortExpression` value is an `empty string` and `newList` gives out the `data` and is not null. I have posted the screen shots in the above post for your inspection man.. how can we tackle the `Object reference not set to an instance of an object` error? and you're the best man!!!!!! – pv619 Apr 14 '14 at 15:02
  • what is the value for "jtSorting" when you get this exeception? – CHash11 Apr 15 '14 at 05:07
  • thanks @Chah_Mike - this is all I am getting when I put a `break point` in, `debug` and do `quick watch` for `jTSorting` [Screen shot](http://s22.postimg.org/gcu4xofdd/sort_Expression1.png). Looks like to be an `Empty` string. But on the View I get `Object reference not set to an instance of an object`. Can't believe that you're still helping me on this.. really appreciate it man :) – pv619 Apr 15 '14 at 06:44
  • before debug when I hover over `jtSorting` I get the value `(parameter) string jtSorting` and during debug when I hover over, I get `Times ASC` value for `jtStoring`. Here's the [Screen shot](http://s13.postimg.org/813cobgev/sort_Expression2.jpg).. and thanks a billion :) – pv619 Apr 15 '14 at 06:57
  • add this before SortDirection declaration `if (string.isNullOrEmpty(jtSorting)) { jtSorting = "Date ASC"; }` – CHash11 Apr 15 '14 at 08:37
  • EDIT: thanks for getting back :) I did what you suggested but it still gives the same error out `Object reference not set to an instance of an object.` – pv619 Apr 15 '14 at 08:38
  • I have updated my full code above for your inspection in the post above.. are we missing out something? thanks again man you're the best!!! – pv619 Apr 15 '14 at 08:45
  • EDIT: I disabled `\\ defaultSorting: 'Times ASC',` in the `View` and now the `jtSorting` value in `Controller` `debugger` shows `null.` So `jtSorting` is picking the `Value` from the `View` but actually not doing anything and giving out the `Object reference not set to an instance of an object.` error. – pv619 Apr 15 '14 at 08:52
  • there is typo in one line, corrected it to ' string sortExpression = sortDirection == SortDirection.DESC ? jtSorting.ToLower().Replace(" desc", "") : jtSorting.ToLower().Contains(" asc") ? jtSorting.ToLower().Replace(" asc", "") : jtSorting;' – CHash11 Apr 15 '14 at 08:57
  • thanks @CHash_Mike - i rectified what you suggest but still getting the complex `Object reference not set to an instance of an object.` – pv619 Apr 15 '14 at 09:06
  • sorry to keep bugging you man but do you think of anything else what do we be missing out? – pv619 Apr 15 '14 at 12:40
  • You need to find out which line is causing Object reference issue.. That particular varaible whichever is null, needs to be initialized, thats the only solution – CHash11 Apr 15 '14 at 14:01
  • thanks for that and sorry to keep on bugging you.. appreciate all your help. Sorry, I find it hard to learn new languages and small things like this making it soo complex for me to get it to work. `sortExpression` and `jtSorting` variables are both `nulls` and this `newlist = newlist.OrderBy(item => GetPropertyValue(item, sortExpression)).ToList();` of the code is giving out the `Object` reference. crazy hard man - `sortExpression` is already initialize though is it? – pv619 Apr 15 '14 at 14:25
  • Please mark the answer if your originally asked question was answered correctly. – CHash11 Apr 21 '14 at 12:50
  • Hi, it's still not working.. will you help out for one last time please? I deggued the code and `sortExpression` and `jtSorting` variables are both null.. could you help to initialize both with values please? I exactly don't know how to do that.. thanks and hope you help. – pv619 Apr 22 '14 at 06:42
  • are the sortExpression and jtSorting variables always null or only in certain case? – CHash11 Apr 22 '14 at 13:41