Couple of weeks ago, i had an email from a customer of ours who wanted to know how to provide a external search box to our Kendo UI grid. What they wanted to do was to have a text box and a button to initiate the search. This seems to be a common scenario that you will have in your proejcts. So i thought this makes a good case for a blog post. If you have a similar situation in your projects then you better read through this blog post till the end.
What i want to achieve is:
- Have a text box to enter a search string
- Have a button which will trigger the search
- Have a Kendo UI Grid to show the data
I will be using our Northwind OData service available here: http://demos.telerik.com/kendo-ui/service/Northwind.svc/. I will be using the Customers data to show in the grid and search
Setting up the UI:
Binding the Grid with Data:
On document ready, i will instantiate the Kendo UI Grid and bind it to the Odata service. Here is the code snippet:
Lets walkthrough as to what has been done. I provide a datasource to the grid . I set the page size to 20 and turn on server paging & server filtering so that the data source does not do client side paging & filtering. I also provide the grid with the columns that needs to be shown.
Handling Search Button Click:
As stated earlier, the external search will be triggered by the search button we have above the grid. If you thought that the Grid is what will be doing the search – well its not. Its actually the data source will do the heavy lifting. The Grid just gets the data to display from the data source. Now, the Grid’s data source is of type kendo.Data.DataSource. One of the API methods that the data source provides is query(). What query method does is – it will execute any specified query and will make a HTTP request when bound to a remote service. So the query we need to perform in our case is filtering. Our search text needs to be converted in to a bunch of filters. In my use case i would like to search the fields Company Name, Customer Name and Contact Name whether they contain the text entered in the search box. So this will be specified as 3 filter conditions with an “OR” logic. So here is the code snippet to do this:
Well that’s all the code it takes you to provide a external search capability for your grid.
You can see a working demo here: http://runner.telerik.io/fullscreen/@kashyapa/IhEr/5
You can get the source code of this demo is available here: http://dojo.telerik.com/@kashyapa/IhEr/5
I think this post gives you an idea on the power of kendo.data.DataSource. You can do a lot of things with data source. Hope this example helps you in your project if you have a similar requirement.
Till next time, Happy Coding!