Send DataSourceRequest with JavaScript function

1 Answer 1416 Views
Grid
Paweł
Top achievements
Rank 1
Paweł asked on 20 Mar 2014, 07:40 AM
Hello,
I have following grid:

@(Html.Kendo().Grid<Dto.ReportTimeStatDto>()
 .Name("ReportGrid")
 .Columns(columns =>
 {
    columns.Bound(c => c.BusinessProcess).Width(100);
    columns.Bound(c => c.WorkName)).Width(150);
    columns.Bound(c => c.CreationDate).Width(130);
    columns.Bound(c => c.TimeLimitDate).Width(130);
    columns.Bound(c => c.FinishDate).Width(130);
  })
  .AutoBind(false)
  .Scrollable()
  .Resizable(r => r.Columns(true))
  .Groupable()
  .Sortable()
  .Filterable( )
  .Pageable(pageable => pageable
 .Refresh(true)
 .PageSizes(true)
 .ButtonCount(5))
  .DataSource(dataSource => dataSource
    .Ajax()
    .Read(read => read.Action("Read", "ReportTimeStat"))
    .Model(model => model.Id(m => m.Id))
   )                                
   )

and I have just a simple button:
<button id="statistics" type="button">Statistics</button>

I would like to achieve this scenario:
When user clicks statistics button I would like to pass DataSourceRequest to WebApi Controller. Then I would like to read all data (change pageSize to total count of records) with current filters set on grid and count average value of data from one of the columns.
I have problem with passing DataSourceRequest to my method in controller. I tried sending
$("#ReportGrid").data("kendoGrid").dataSource.filter()
object, but it's a bit different from DataSourceRequest so it's not working.
How could I solve this problem?
Paweł
Top achievements
Rank 1
commented on 20 Mar 2014, 10:52 AM

I also tried sending
$("#ReportGrid").data("kendoGrid").dataSource._params()
but still - it's not the same object as C# DataSourceRequest so it won't work.

1 Answer, 1 is accepted

Sort by
0
Vladimir Iliev
Telerik team
answered on 24 Mar 2014, 08:34 AM
Hi Marcin,

In current case you can use the Grid build-in parameterMap function to format correctly the needed options from the DataSource - please check the example below:
function sendData() {
    var grid = $("#Grid").data("kendoGrid"),
        parameterMap = grid.dataSource.transport.parameterMap;
 
    var data = parameterMap({ sort: grid.dataSource.sort(), filter: grid.dataSource.filter(), group: grid.dataSource.group() });
    $.ajax({
        url: "/Home/UpdateCreateDelete",
        data: data,
        type: "POST",
 
Regards,
Vladimir Iliev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
EdsonF
Top achievements
Rank 2
commented on 27 Aug 2014, 11:38 AM

Hi Vladimir

I'm trying to do the same but to download an exported xlsx file.

this is what I'm doing on my javascript:

exportData = function () {

        var grid = $("#QuoteGrid").data("kendoGrid");
        var parameterMap = grid.dataSource.transport.parameterMap;
        var sortData = grid.dataSource.sort();
        var filterData = grid.dataSource.filter();
        var groupData = grid.dataSource.group();        
        var data = parameterMap({ sort: sortData, filter: filterData, group: groupData });
        var request = $.toJSON(data);
        location.href = CUSTOMER_QUOTES_EXPORT_URL + "?request=" + request;                
        return false;
    }

But still my controller end point does not contain the filters, etc passed in the call

public FileResult ExportQuotes([DataSourceRequest]DataSourceRequest request)


What I'm doing wrong ?
Vladimir Iliev
Telerik team
commented on 29 Aug 2014, 04:21 AM

Hi Edson,

From the provided information it seems that you are building the query string parameters incorrectly which is the reason for current behavior. In current case I would suggest to check the following examples in our CodeLibrary which demonstrates how to successfully export the Grid data to excel file:

Regards,
Vladimir Iliev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
EdsonF
Top achievements
Rank 2
commented on 29 Aug 2014, 08:38 AM

Thank you very much Vladimir!

You guys have the best set of controls known to human kind - Kendo UI rocks!

Regards

Edson
Jim
Top achievements
Rank 1
commented on 05 Mar 2015, 07:51 PM

Hi Vladimir.  In the case for Marcin, it looks like you are using parameterMap to post back to the controller the request info that went into creating the currently displayed set of records for the grid.  This is exactly what i need, but what would the controller post handler method signature in Home::UpdateCreateDelete(  xxx ) look like?

and can you pass the page size, total and, page number fields as well, since they are part of the DataSourceRequest object?
Vladimir Iliev
Telerik team
commented on 06 Mar 2015, 09:37 AM

Hi Jeff,

You can check the example Controller Action signature below:

public ActionResult ExampleAction([DataSourceRequest] DataSourceRequest request)
{

Also you can pass all properties which are part of the DataSourceRequest object. They can be get using the dataSource client side API:

Regards,
Vladimir Iliev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
Raj
Top achievements
Rank 1
commented on 09 Jan 2018, 09:09 PM

Hello Vladimir

How to post other parameters along with DataSourceRequest, Iam able to post other parameters but the DataSourceRequest values are null.

if i take off other parameters and post only DataSourceRequest it works. 

Posting DataSourceRequest with other parameters doesnt work?

Any ideas?

Raj

Viktor Tachev
Telerik team
commented on 10 Jan 2018, 12:21 PM

Hello Raj,

In order to pass additional parameters to a Read/Update/Create action you can use the Data() method. Please check out the article below that describes the approach:



Regards,
Viktor Tachev
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Raj
Top achievements
Rank 1
commented on 10 Jan 2018, 02:35 PM

Thanks for the response

Iam already aware of that passing parameters using Data() method, but thats for only read/update/create.I want to send DataSourceRequest along with other Parameters from custom javascript (using Ajax) to custom action Method, not the Read/Update/Create action that were used in the grid.

Something like this.

var grid = $("#Grid").data("kendoGrid"),
        parameterMap = grid.dataSource.transport.parameterMap;

    var data = parameterMap({ sort: grid.dataSource.sort(), filter: grid.dataSource.filter(), group: grid.dataSource.group() });
    $.ajax({
        url: "/Home/UpdateCreateDelete",
        data: {

data,

otherParameter: someId,

oneotherParam: someString

},
        type: "POST",

 

Note that its a custom action method not the grids Read/Update/Create action.

 

Raj

Viktor Tachev
Telerik team
commented on 12 Jan 2018, 09:28 AM

Hello Raj,

The DataSourceRequest is used in the CRUD methods as it is used by the DataSource of the Grid component. When passing DataSourceRequest to the server you can include all built-in properties that are part of the DataSourceRequest object. Additional data can be sent in a separate field like you are doing in the sample code from your last post. 

Regards,
Viktor Tachev
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Raj
Top achievements
Rank 1
commented on 12 Jan 2018, 02:04 PM

Thank you,

But the values posted in DataSourceRequest object are null if i send additional data in separate field.

Please provide a sample code

Raj

Viktor Tachev
Telerik team
commented on 16 Jan 2018, 12:37 PM

Hello Raj,

The DataSourceRequest contains data that is relevant in an action that would read or update data in the Grid. 

Would you elaborate in more detail on what is the functionality that you would like to implement? Why do you need to call an Action that is not related to a Grid and pass DataSourceRequest to it?


Regards,
Viktor Tachev
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Raj
Top achievements
Rank 1
commented on 16 Jan 2018, 08:31 PM

Okay

Here is the situation, I have a grid with virtualscrolling enabled with pagesize 100 and serveroperations true. Data in grid is large with 20,000 - 30,000 rows. 

I want to filter the data by column something like (column contains) which gives me back lets say some 5000 rows and i want to delete all of them.

But since i have a pagesize of 100 i can only capture 100 rows from DOM using JS. 

Now What Iam planning to do is Pass DataSourceRequest to controller along with some other parameters which are required for data pull from DataBase, once i get the data back from Database (which is all original data like 20,000-30,000 rows) i would apply the passed DataSourceRequest to the List which then gives me the filtered data (around 5000). Now i have filtered data in my controller and i can use their ids to do a bulk delete at a time.

Additional Parameters are required for original Data pull from Database and DataSourceRequest is required for filtering the data.

Thanks

Raj

Viktor Tachev
Telerik team
commented on 18 Jan 2018, 02:58 PM

Hi Raj,

Based on the description it is not necessary to pass the entire DataSourceRequest to the server as it contains additional data that will not be used. You can retrieve just the applied filters and send them to the server. Make sure that you call JSON.serialize() for them before passing them to the server action. 

var filters = JSON.stringify($("#grid").getKendoGrid().dataSource.filter().filters)
 
$.ajax({
        url: "/Home/CustomActionMethod",
        data: {
 
        filterParams: filters,
 
        otherParameter: someId,
 
        oneotherParam: someString
 
        },
 
// other options
})


Regards,
Viktor Tachev
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Raj
Top achievements
Rank 1
commented on 22 Jan 2018, 10:26 PM

HI Viktor

That didn't work, Please find attached image. Posted values are null. Like you said i called JSON.stringify also.

Raj

 

Viktor Tachev
Telerik team
commented on 24 Jan 2018, 01:41 PM

Hello Raj,

What I meant in my previous reply is that there is no need to use to use DataSourceRequest in the custom ActionMethod since it will not be necessary.

The CustomActionMethod would look similar to the following:


public ActionResult CustomActionMethod (string filterParams)
{
     
}


The relevant fields can be passed using Ajax:


var filters = JSON.stringify($("#grid").getKendoGrid().dataSource.filter().filters)
  
$.ajax({
        url: "/Home/CustomActionMethod",
        data: {
  
        filterParams: filters
  
        },
  
// other options
})


Regards,
Viktor Tachev
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Raj
Top achievements
Rank 1
commented on 24 Jan 2018, 03:16 PM

Thanks

Okay how do i filter from my list in controller using that (filterParams). Please provide code sample.

Thanks

Raj

Viktor Tachev
Telerik team
commented on 26 Jan 2018, 10:17 AM

Hello Raj,


When the filter conditions are available on the server you can use them to construct a query and request the relevant information directly from the database. You can use different approach depending on your setup and preferences. 

The thread below discusses how data can be read using SqlConnection:


The article below illustrates how to get data using EntityFramework:



Regards,
Viktor Tachev
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Mike
Top achievements
Rank 1
commented on 06 Nov 2018, 12:02 AM

I'm also attempting to do this.  It seems like the simplest solution would be to pass the filters from the grid to a custom controller, then process the filter on the server using the extension method .ToDataSourceResult() with the Telerik filter processing already built in.  From there, we could then just take the result and create the excel spreadsheet.

This allows for us to export large datasets server-side.

 

The problem I run into is the same as above....the DataSourceRequest is null.  In my case, I can get the page and pagesize (not important), but the filters property is always null.

 

var data = parameterMap({ sort: grid.dataSource.sort(), page: grid.pager.page(), pageSize: grid.pager.pageSize(), filters: grid.dataSource.filter(), group: grid.dataSource.group() });

 

That's what I've used to generate the request property when sending via ajax.

Viktor Tachev
Telerik team
commented on 06 Nov 2018, 12:07 PM

Hello Mike,

Try sending the filters like illustrated in the code snippet below and let me know how it works for you.


var filters = JSON.stringify($("#grid").getKendoGrid().dataSource.filter().filters)
   
$.ajax({
        url: "/Home/CustomActionMethod",
        data: {
   
        filterParams: filters
   
        },
   
// other options
})


Regards,
Viktor Tachev
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Giovanni
Top achievements
Rank 1
commented on 05 May 2020, 01:51 PM

After quite a bit of time and effort, I finally got it to work as follows.
On client:

grid = $("#grid").data("kendoGrid");
var dataSourceRequest = (new kendo.data.transports["aspnetmvc-server"]({ prefix: "" }))
    .options.parameterMap({
        sort: grid.dataSource.sort(),
        filter: grid.dataSource.filter()
    });
var filters = dataSourceRequest.filter;
var sorts = dataSourceRequest.sort;
 
var data = { filters: filters, sorts: sorts, extra: extra };
 
$.ajax({
    type: 'POST',
    url: '@Url.Action("ExportCases", "Tracker")',
    data: data,
    success: function (resultData) {
        downloadExportFile(resultData);
    },
    error: function (resultData) {
        // error message
    }
});

 

Controller:

public JsonResult ExportCases(string filters, string sorts, string extra)
{
    DataSourceRequest request = new DataSourceRequest();
    request.Filters = FilterDescriptorFactory.Create(filters);
    request.Sorts = GridDescriptorSerializer.Deserialize<SortDescriptor>(sorts);
     
    // Now you can use the DataSourceRequest as you normally would

 

B
Top achievements
Rank 1
commented on 05 May 2020, 09:58 PM

@Giovanni - I happened to run into this post looking for the same functionality right after you answered.
Your answer led me in the right direction.

If you change this code (note the object name is singular not plural):

var data = { filter: filters, sort: sorts};

 

Then the controller will accept the call as a regular DataSourceRequest so change your controller as follows:

public JsonResult ExportCases([DataSourceRequest] DataSourceRequest request)

Jeffrey
Top achievements
Rank 1
Veteran
commented on 09 Jun 2020, 03:05 AM

Giovanni

 

This is perfect.  I failed to find the FilterDescriptorFactory and GridDescriptorSerializer Classes.  There are no examples for the server side of the tools. 

The tools are great but sometimes Telerik forgets we need to get the information back to the server.  Having the sort and filter in Datasource Request Form makes filtering and sorting in c# easy since we already handle it this way for the grid.  

Thanks,

Jeff

Tags
Grid
Asked by
Paweł
Top achievements
Rank 1
Answers by
Vladimir Iliev
Telerik team
Share this question
or