Wednesday, November 30, 2011

Sorting and Filtering Data Set with JavaScript and jQuery.

When working with potentially large corporate data sets, filtering and sorting should be done at the back end with ajax call.  Even though, filtering and sorting can be done cleverly by JavaScript, potential for downloading large data set and problems with the IE8 JavaScript error (O^2) can catch up with you.  I don't recommend joining, merging, and other sql-like operations with JavaScript.  Most sorting and Filtering requires at minimum O^2.  


Also, when building a grid that reads any data set, the endpoint should always have paging related parameters like PageNumber, PageSize, and few others.  The only part of the data set that's relevant to the current display should be retrieved.  Data joining should not be done at the web UI level.


$.ajax({
    type: "POST",
    url: "http://localhost:5000/Search/GetData",
    data: JSONData, 
}).done(function (msg) {
    alert("Data Saved: " + msg);
});


For the JSONData, you could build out a string that matches with the class signature, DataContract


public class SearchResult
{
    public JsonResult data { getset; }
    public int PageNumber { getset; }
    public int PageSize { getset; }
    public int PageCount { getset; }
    public int DataCount { getset; }
}



public class SearchPackage
{
    public SearchItem[] Items { getset; }
    public int PageNumber { getset; }
    public int PageSize { getset; }        
}



 public class SearchItem
 {
     public string FieldName { getset; }
     public string Value { getset; }
     public SortDirection SortDirection { getset; }
 }

var JSONData = { "SearchItem": [
"fieldName""LastName""value""Smith""sortDirection""SortDirection.ASC" },
{ "fieldName""FirstName""value""John""sortDirection""SortDirection.DESC"}]};

If you are passing an url value for the data, you can do

url: "http://localhost:5000/Search/GetData?fieldNames=LastName&fieldNames=FirstName&values=Smith&values=John&sortDirections=SortDirection.ASC&sortDirections=SortDirection.Desc";

[HttpPost]
public JsonDataResult GetData(List<string> fieldNames, List<string> values, List<int> sortDirections)
{
     using (var proxy = searchFactory.CreateChannel())
    {
     SearchResult oSearchResult = SearchFactory.GetRequestPackage(Transform(fieldNames, values, sortDirections));      return Json(oSearchResult );
    }
}

Since there are two parameters called the fieldNames, such parameters is like passing a List fieldName.





No comments: