Telerik blogs

What is RadClientDataSource?

The control is server-side wrapper of the popular DataSource widget, part of Telerik® HTML5 and JavaScript framework, Kendo UI® framework. The ASP.NET Web Forms control exposes most of the main settings as easily configurable properties. With just a few lines of code, you get a working setup that can extract data from almost any kind of web service out there. We also support various data formats, such as JSON, JSONP and XML. Getting the right configuration for the particular service is fast and easy, and you get data in a convenient form right there on the client, so you can process it as you find best.

What’s better is that most of the databound controls from the Telerik® UI for ASP.NET AJAX already support full integration and client-side databinding through the ClientDataSource. All you have to do is hook up a control to the ClientDataSource by using the ClientDataSourceID property, and your data is presented in a nice and suitable way.

You can check out the introduction demo of the control here.

Basic Configuration and Properties

The ease of use of the ClientDataSource control is only matched by its power data operations capabilities. It allows you to manage your client-side data in ways that were not possible before. Starting with the basics such as sorting, filtering and paging, and getting to advanced operations such as data grouping and batch updates, it allows you to manipulate multiple records of data at once. Its useful client-side events take it up a level by providing full customization of the queries and parameters passed to the web service. 

We will go through some of the basic configuration and options in the control so you can see how fast and easy it can be configured.

Web Service Settings

One of the main and most important settings is of course the actual connection of the web service. This can be achieved easily through the WebServiceDataSource property, enabling quick set-up of the main operations performed with the web service. Below is a sample configuration:

<telerik:RadClientDataSource runat="server" ID="RadClientDataSource1">
   <DataSource>
      <WebServiceDataSourceSettings BaseUrl="http://demos.telerik.com/kendo-ui/service/">
           <Select Url="Products" DataType="JSONP" />
           <Update Url="Products/Update" RequestType="Post" DataType="JSONP" />
           <Insert Url="Products/Create" DataType="JSONP" />
           <Delete Url="Products/Destroy" DataType="JSONP" />
As you can see, there are four sub-settings corresponding to each type of operation: Select, Update, Insert and Delete. Each one can be further customized with URL, DataType and RequestType properties.

Data Model Settings

The next important setting is related to the data representation and scheme. It further defines the fields we can expect coming from the service as well as their type and additional restrictions such as Editable, Nullable and so on.
  • Schema: Common settings for identifying different parts of the response such as DataName, ErrorsName, ResponseType, GroupsName and more.
  • Model: As a direct child of the Schema, this setting holds a collection of fields coming in the web service response. It also defines the model ID field used during CRUD operations.
  • ClientDataSourceModelField: Represents an object containing settings for each model field such as FieldName and DataType as most important.
Below is a simple example:

<Schema >
   <Model ID="ProductID">
      <telerik:ClientDataSourceModelField  FieldName="Discontinued" DataType="Boolean" />
      <telerik:ClientDataSourceModelField FieldName="ProductID" DataType="Number" />
      <telerik:ClientDataSourceModelField FieldName="ProductName" DataType="String" />
      <telerik:ClientDataSourceModelField FieldName="UnitPrice" DataType="Number" />
      <telerik:ClientDataSourceModelField FieldName="UnitsInStock" DataType="Number" />
   </Model>
</Schema>

Sort, Filter and Group Expressions

The ClientDatasSource control also provides various options for further manipulating the requested data by applying different sort filter and group expressions. Their syntax follows a common structure: the control has three corresponding collections, respectively, for Sort, Filter and GroupExpressions.

The sort expressions have two basic properties: FieldName and SortOrder, as shown below:

<SortExpressions>
      <telerik:ClientDataSourceSortExpression FieldName="Field1" SortOrder="Asc" />
</SortExpressions>

The group expressions are defined in a similar way but they also support an inner Aggregates collection that can be used to specify one or more aggregates to be calculated for each field. Here is a simple example:

<GroupExpressions>
     <telerik:ClientDataSourceGroupExpression FieldName="Field1" SortOrder="Asc">
         <Aggregates>
              <telerik:ClientDataSourceAggregate Field="Price" Aggregate="Average" />
         </Aggregates>
     </telerik:ClientDataSourceGroupExpression>
</GroupExpressions>

The filter expressions collection is a little more complex as it also supports nested filtering, enabling more elaborate filter queries to limit the data records. 

The main filter setup starts with the FilterExpression property, which, in turn, may contain a simple FilterEntry or another nested FilterExpression. The FilterEntry is defined by FieldName, Operator and Value, while the FilterExpression has additional LogicOperator defining whether the expressions will be connected by an AND or OR operator. Below is a sample setup:

<FilterExpression LogicOperator="Or">
    <telerik:ClientDataSourceFilterEntry FieldName="Field1" Operator="Contains" Value="Test" />
    <telerik:ClientDataSourceFilterExpression>
         <telerik:ClientDataSourceFilterEntry FieldName="Field2" Operator="GreaterThan" Value="5" />
         <telerik:ClientDataSourceFilterEntry FieldName="Field3" Operator="EqualTo" Value="10" />
    </telerik:ClientDataSourceFilterExpression>
</FilterExpression>

After processing, the configuration above will be translated to the following filter query: 
Field1 Contains “Test” OR (Field2 > 5 AND Field3 = 10).

Finally the last collection is the Aggregates, applied to all the items retrieved by the ClientDataSource control. Again, each item in the collection has a Field and Aggregate property:

<Aggregates>
     <telerik:ClientDataSourceAggregate  Field="Field1" Aggregate="Count" />
</Aggregates>

Client-Side Events

The ClientDataSource also provides an extensive suit of client-side events suitable for all kinds of scenarios and further customizations. Here we have the standard OnRequestStart, OnRequestEnd and OnRequestFail events providing additional information about the state at each stage of the request. Next we have some of the Kendo UI client-side events wrapped, as well: OnChange, OnSync fired when working with batch operations in the control. Then we have OnDataRequested and OnDataParse events fired while the control is processing the data coming from the service. Finally, there is the custom OnCommand event that is fired when the control is performing any kind of operations such as fetching data, paging, filtering and so on. Additional information on the client-side events can also be found in the following help topic.

Client-Side API

As a wrapper of a fully client-side oriented widget, there’s no doubt the ClientDataSource's main focus will be on its rich and versatile client-side API. We will list below some of the main methods used to operate with the control through javascript:
  • get_kendoWidget / get_dataSourceOjbect – used to get a reference to the underlying kendo widget wrapped by the control
  • get / set_pageSize, get / set_allowPaging and get / set_currentPageIndex used to modify the paging related properties of the control and retrieve a spefic portion of the data
  • get_schema – gets the schema object of the data source identifying fields and types
  • get_transport – gets the underlying settings for connection to the web service
  • get_sortExpressions, get_filterExpressions, get_groupExpressions and get_aggregates serve to get the respective collection of settings for expressions in questions
  • get_totalItemsCount, get_totalPagesCount gets the overall number of records and pages returned from the service
  • view:  a method that returns the data items which correspond to the current page, filter, sort and group configuration
  • fetch:  a method which returns data from the web service after calling the select method from the transport settings
  • sync:  persists any data item changes to the data source and calls the respective CRUD methods from the transport
  • inser, add:  methods to add a new record to the data source collection of the data items
  • update: updates a record by given ID
  • remove: removes a record by given ID
Additional information can also be found at the following help topic.

Piecing It All Together–A Runnable Example

We will finish this blog post with an integration example of RadGrid and ClientDataSource working together to provide a rich user experience.

Below, we will have a look at a real-life scenario, in which you may need to pass additional parameters to the web service or just  avoid the heavy processing of large data on the client-side. In this case, the best option is to use the OnCusotmParameter client-side event of the control. It gives you the capability to pass any parameters you wish in the format that your service expects. Easy to use, the event requires only a simple JSON formatted string defining the necessary parameters and their values. Additionally, you can check the type of the request sent to the data service (for example, whether it is a read, update or delete request). Below is a sample code snippet:

function ParameterMap(sender, args) {
    if (args.get_type() != "read") {
 args.set_parameterFormat({ parameterName: parameterValue });
  }
}

This also comes in handy when you wish to leave some of the data processing on the server side by the service instead of the ClientDataSource control. These capabilities can be enabled easily by setting the EnableServerFiltering, EnableServerSorting or EnableServerPaging properties. Then, you need only pass the required parameters in the event above, and you are good to go. A sample runnable project showing this approach is also attached at the end of this blog post. Feel free to give it a try.
A second very useful event is OnDataParse, which allows you to easily shape your data coming from the service in the expected format. This is especially useful if you are working with WCF services, where, oftentimes, the data comes wrapped in additional amounts of JSON-specific service properties. Below is a sample code showing how to strip out the data collection in this case and pass it directly to the ClientDataSource:

function Parse(sender, args) {
    var response = args.get_response().d;
    if (response) {
         args.set_parsedData(response.Data);
     }
}

Conclusion

Some of the other databound controls fully supporting client-side databinding and integrations with the ClientDataSource are ListView for ASP.NET AJAX as shown in this online demo, and also one of the newest additions to the suitе--the DataForm control.

The examples in this post are only a small part of the constantly growing group of controls featuring easy client-side databinding through the ClientDataSource control. And as of Q1 2015, that number has risen to more than 17 different controls. Feel free to check the detailed examples in our online demos, and bring in easy data management and smooth user experience to your applications.

 

A sample application can be downloaded here.


About the Author

Marin Georgiev

is a software developer in one of Telerik's ASP.NET AJAX Teams. Since he joined the company in 2010 he's been working on different client-side features and extending the mobile support of the controls. His interests include mobile and web development as well as integration with Sharepoint 2010.

Related Posts

Comments

Comments are disabled in preview mode.