Single Page Binding with Kendo UI ListView

If you’ve looked at the demos on the Kendo UI site, you’ll notice the ListView and DataSource combination are a pretty capable combination. The ListView gives you full control over the user interface, while supporting common functionality like paging, sorting, and more. The DataSource provides read and update functionality to a local or remote data source, even giving you full control over these processes (for instance, you can use JQuery directly for AJAX communication). The pager natively pages through the contents of the listview automatically for you. The three widgets offer great functionality for the developer.

While the combination works well, I personally ran into a snag using the Kendo UI core version (open source). With the pager component natively paging the content, the data source required a complete dataset downloaded from the server. If your ListView will be presenting 30 records, all 30 must be retrieved from the server; if 3,000, all 3,000 must be retrieved from the server. Now natively the data source control supports server paging, most examples illustrated using the Telerik MVC wrappers for handling the server-side processing, and as such, I wasn’t sure whether it was supported. If it works, I would recommend using the kendo pager as it offers the smoothest navigation; but if not, this workaround worked just as well, with some added effort. In order to get around this, I ended up using the Bootstrap Paginator plugin.

The bootstrap paginator allows you control over the number of pages to show, and provide delegation on user interaction, with the example below.

$('#pager').bootstrapPaginator({
            currentPage: 1,
            totalPages: 10,
            onPageClicked: function(e, evt, type, page){
                //Reload the listview - listview uses custom AJAX option
                #("#listview").data("kendoListView").dataSource.read();
            }
        });

The currentPage option sets the current page in the list, within the range of total pages. It’s possible to preload these from an MVC model, especially when you factor in postbacks (the pager needs reinitialized on postbacks), as in the following:

{
   currentPage: @Model.CurrentPage,
   totalPages: @Model.TotalPages
}

When the user clicks on a page, it fires the onPageClicked callback handler, which subsequently triggers an AJAX action back to the server. We’ll need the new page index from the event handler; we can get it directly from the plugin, or store the current index in a hidden variable. Either way, this piece of information needs passed back to the server.
If you looked in the example online, it has a custom AJAX action as shown below.

$("#listview").kendoListView({
    dataSource: {
       transport: {
           read: function(o) {
              var index = // Get index from hidden variable or wherever

              $.ajax({
                  type: "post",
                  url: "@Url.Action("Action", "Controller"),
                  data: { index: index, otherParams: "OTHER PARAMS" },
                  success: function(d) { o.success(d); },
                  error: function(d) { o.error(d); }
              }); 
              
           }
       }
    }
});

Here we trigger the postback to the server, and pass in the list of form data values, as well as the currently selected page index. Since the items per page is hard-coded in this scenario (at say 10, for example), we can quickly calculate the starting index and ending index of the current page.

There are many ways to implement this solution; this is one quick, simple way to introduce paging with large lists of data, where each page is dynamically loaded at paging time.

Advertisements

Kendo UI Lists and Twitter Bootstrap Simplified

Bootstrap is a great CSS layout framework for setting up the user interface of your application. Bootstrap provides a grid system, whereby content can be structured into a grouping of columns up to a maximum of 12 total. This works great for laying out content, and can also be useful for layout out content in grids too. The following is an example of defining a template. Kendo uses templates to define the item view for the list. The following is a row within the eventual list rendered vertically:

<script type="text/x-kendo-template">
  <div class="row">
    <div class="col-md-3">
      #: FirstName #
    </div>
    <div class="col-md-4">
      #: LastName #
    </div>
    <div class="col-md-2">
      #: State #
    </div>
    <div class="col-md-3">
      <a href='@Url.Action("Where", "Some")/#=ID#'>
        View
      </a>
    </div>
  </div>
</script>

Next, we need to use the template, which we would supply to the kendo listview initialization plugin. Below is the initialization of the list, as well as the passing of the template to the list:

<div id="listview"></div>

  $(function() {
    $("#listview").kendoListView({
       autoBind: false,
       dataSource: new kendo.data.DataSource(..),
       template: kendo.template($("#template").html())
    });
  });

Notice our listview doesn’t need to define anything special; it gets built up by the kendoListView widget. The initialization properties passed are disabling auto binding on init (manual binding occurs later, which is good for views that need the user to interact with a form first). It also defines a data source and supplies our template.

The listview then binds the data, grabbing each record and generating a collection of <div class=”row”> objects, one for each record of data. That’s all that it takes to use the listview to bind a collection of rows using the bootstrap styles. Now when the screen collapses, each cell also collapses into it’s own row.

Using the Telerik RadDropDownList Control for Windows Store Apps (HTML/JavaScript)

I previously wrote about using the Telerik RadAutoCompleteBox control for Windows Store apps. We’re going to look at another control, which is the RadDropDownList control. This control is as simple as the RadAutoCompleteBox, and I’m going to include some additional steps not mentioned previously. So let’s get started. To begin, we need to add a reference to the Telerik.UI.DLL, which is available once you downloaded and installed the Windows 8 components.  Once installed, you can add a reference to it by right-clicking references, selecting “Add reference”.  It should appear in the extensions list.

Once you have this, we need to add some references to scripts and styles, as shown next:

<link href=”///Telerik.UI/css/common.css” rel=”stylesheet” />
<link href=”///Telerik.UI/css/dark.css” rel=”stylesheet” />
<script src=”///Telerik.UI/js/jquery.js”></script>
<script src=”///Telerik.UI/js/ui.js”></script>

Notice the triple slash at the beginning of the script.  This is the assembly notation.  This signals to the Windows framework to look in Telerik.UI.dll for the associated CSS and JS files, similar to how we pull out embedded references in the ASP.NET AJAX framework.

Next, we need to add a reference to the control in the page:

<span id=”Group” data-win-control=”Telerik.UI.RadDropDownList”
data-win-options=”{dataTextField:’GroupName’,dataValueField:’GroupUserName’,autoBind:false}”></span>

Here we create a new RadDropDownList and initialize the field names, which are pointers to fields in the objects bound to the list.  Next, the autoBind feature signals not to automatically bind on load.  This is because, in this example, we’re going to programmatically bind the grid.  I do so first by making a call to a backend service:

WinJS.xhr({
type:”get”,
url: “..”,
headers: { “content-type”: “application/json” }

})
.then(

function(d) {

var data = JSON.parse(d.response);
var dataSource = new Telerik.Data.DataSource(data);

var group = document.querySelector(“#Group”).winControl;
group.dataSource = dataSource;

}
);

Using the xhr function to make an XML HTTP request, the established JSON data returned from the backend service is passed to the Telerik data source and bound to the control.  Instead of binding from code, we can also bind data inline, as illustrated in the following example.  Below is a snapshot of an example created in the telerik sample documents.

<span id=”Span1″ data-win-control=”Telerik.UI.RadDropDownList” data-win-options=”{
dataSource: [
{ category: ‘Green’, color: ‘#7AD36A’, border: ‘#3A7E2B’ },
{ category: ‘Interesting’, color: ‘#9CB6E7’, border: ‘#28518E’ },
{ category: ‘Orange’, color: ‘#F9BA89’, border: ‘#B14F0C’ },
{ category: ‘Purple’, color: ‘#B6A2E3’, border: ‘#4C318E’ },
{ category: ‘Red’, color: ‘#E6A0A1’, border: ‘#A61C22’ },
{ category: ‘Yellow’, color: ‘#FCFA90’, border: ‘#A0981D’ }
]
}”></span>

I hope this was a good illustration of the Telerik RadDropDownList control, and how easy it is to use in your projects.

Using Telerik RadAutoCompleteBox for Windows 8 (HTML)

In this post, we’re going to look and see how ridiculously easy it is to add auto complete behavior functionality, as demonstrated in the sample application built for the Windows 8 controls. If you haven’t done so already, download the RadControls for Windows 8 sample demo available in the Windows Store. This sample application comes with control demonstrations and sample code, which is also available when you download the source control.

First, we need an input element, as shown below.

<input class=”Member” type=”text” data-win-control=”Telerik.UI.RadAutoCompleteBox” />

Technically, we don’t need an input control, as we could also use a span element. The more important factor of this element definition is the data-win-control property, which specifies that it is a RadAutoCompleteBox control. This is a standard Windows 8 declaration of a control. Microsoft includes a variety of other types of data properties for specifying other settings, like data-win-bind for binding data to the view, data-win-options for providing initialization options, and much more.

Using the data-win-options property, the RadAutoCompleteBox control allows us to supply several properties directly in the markup. For instance, my control could have used the following setup, taken from the Telerik examples:

data-win-options=”{
dataSource: {data: Telerik.QSF.HTML.Examples.AutoCompleteBox.Configurator.countries},
height: 330,
minLength: 2,
dataTextField: ‘title’
}”

These additional examples save us from supplying additional information in code. However, if we need that finer control, the RadAutoCompleteBox has a server-side API. For instance, to bind a collection of JSON objects to the autocomplete, all we need to do is the following.

var members = items.querySelector(“.Member”).winControl; //find the control by CSS class
var _members = new Telerik.Data.DataSource( .. );
member.dataSource = _members.dataSource;

Similar to how Windows Store Apps use a WinJS.Binding.List for it’s binding purposes, Telerik also has it’s own binding list, which is a DataSource control. JSON that was streamed from the database server is sent to the client, wrapped in a DataSource object, and linked to the control.

And that is it; that’s all that it takes to wire up the AutoComplete control.