Kendo UI Core and DropDownListFor

Kendo UI Core supports data attribute initialization of its widgets. This initialization approach is largely created for it’s MVVM capabilities, but also can be used for server-side approaches too, which in turn can be used with ASP.NET MVC HTML helpers. The setup may be a little different than you are used to.

Please note: Although Telerik has MVC wrappers already created and ready for you to develop with, these come with the licensed version of the product and are not available through the Kendo UI Core license.

To begin, let’s look at how we’d setup the dropdownlist as an HTML widget without and use of the server.

<select id="reasonID" data-role="dropdownlist" data-option-label="-Select Reason-" data-value="">
  <option selected="selected" value="">-Select Reason-
  <option value="1">Entered in Error
  <option value="2">Removed
</select>

In our example, a select element with a pre-defined list of options is wrapped with the kendo dropdownlist widget. It’s initialized via the data-role attribute, indicating it’s a dropdownlist widget. Next, it defines options that the widget supports. Most of the attributes on the widget that you would configure through the JavaScript API can be defined here, but the syntax differs sometimes (for instance, the optionLabel property you would use in JS initialization is data-option-label in data attribute initialization). If you run into an issue, I was able to find what I needed online so far.

Telerik has some documentation on data attribute initialization here.

The dropdownlist widget can use a textbox as the source, and can also wire data up using JSON via local JavaScript API of via AJAX if you like. I’ve stuck with a select because I’m using the MVC DropDownListFor widget, and to get this widget to render the correct content that I needed, I had to use the following configuration:

@Html.DropDownListFor(
      i => i.ReasonTypeID,      
      Model.ReasonTypes, 
      new
      {
           data_role="dropdownlist", 
           data_option_label="-Select Reason-", 
           data_value=(Model.Receiving.ShrinkTransactionTypeID.HasValue ? Model.Receiving.ShrinkTransactionTypeID.Value.ToString() : ""), 
           style="width:100%;" })

Most of this is standard. The third parameter of DropDownListFor provides HTML attributes to the rendered select option. Here we define the role data attribute used for initialization. The next attribute defines the option label, and the data_value attribute defines the selected value, which is interesting. We already define what’s selected via the lambda expression pointing to our model. However, that’s used to render the selected attribute. What I found is that to cover all selection scenarios (including the default “Select Something” item) is to add the value attribute too, which the widget uses to perform the selection. The code above manually checks for null and converts to an empty string if no value present.

In case you didn’t notice, note how the HTML attribute use data_role, particularly the underscore. The convention that MVC uses is underscore (supported by the language), which is converted to a dash during the rendering process.

Advertisements

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.

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.

Telerik Q1 2014 Released

The latest release for Q1 2014 was includes some features that really caught my eye, and so I’m posting this to share them to you. The first was the new words processing feature for the WPF Telerik framework, a framework that can generate a word document without the use of Word. In my opinion, that is huge, as it is a very useful framework that can even challenge other word processing software products available on the market, now available with DevCraft complete.

The second interesting product was a responsive UI framework available with the Kendo UI framework. A lot of applications make use of some responsive UI framework like Twitter Bootstrap or Foundation by Zurb. Now that Kendo has an offering for this, it’s one step closer to making Kendo a complete product.

PhoneGap, Kendo, and MVVM by Example

I’ve been looking into developing PhoneGap applications. PhoneGap is an excellent tool for getting an application into the app store for iOS, Android, Windows 8/Phone 8, and many other platforms. Since it’s HTML 5 and JavaScript-Based, running on the web browser of the target platform, PhoneGap requires only a single codebase (however, there can be some quirks with the various features, as described in the PhoneGap documentation). Since it’s HTML; you can virtually have whatever design you would like.

However, to go with a minimalist design would not be very user friendly. It’s often best to use a framework like JQuery Mobile, Sensa Touch, or others to handle the look and feel for you. These frameworks provide you with a header and footer similar to apps you would see in the application store, and provide enhanced UI input and layout elements. This is why I chose a framework to lay out the markup for me, and this is also why I chose to use Kendo UI, from Telerik. Kendo UI provides a mobile application framework that supplies a templated UI to the user that completely resembles a mobile application. It also provides a series of input widgets perfect for capturing user input that’s much more appealing ot the user than the standard HTML controlset. It also provides an MVVM framework, and a Single Page Application framework for managing your application’s interaction between the view and model. Note that Kendo comes in three different frameworks: kendo UI web for web controls, Kendo UI Mobile for mobile web applications and PhoneGap, and Kendo UI DataViz, or data visualization components (charting, etc.).

The sample application is the shell we are going to plant into a phonegap application (discussed in a later post). To start, we are going to build is an application containing two views, using data that’s bound to the view via the MVVM framework. In all of my searching on the internet, I had trouble finding a simple example incorporating these exact features, so I hope the following example is a benefit to you. I’ll also describe the Kendo UI framework as I go. To begin, we need to create an HTML page and add some core script definitions to it.

<link href="../../css/kendo.common.min.css" rel="stylesheet" />
<link href="../../css/kendo.bootstrap.min.css" rel="stylesheet" />
<link href="../../css/kendo.mobile.all.min.css" rel="stylesheet" />

<script src="../../js/jquery.js"></script>
<script src="../../js/jquery.migrate.min.js"></script>
<script src="../../js/kendo.all.min.js"></script>

I’ve included the Common, Bootstrap (as in bootstrap theme, not Twitter Bootstrap), and the mobile CSS files. All of these provided allows you to use the Kendo UI web and mobile controls. Additionally, I’ve included JQuery (a requirement of Kendo), which is the latest. The migrate JS file is an add-on that ensures backward compatibility between older versions of JQuery (as of the time of writing, this example used JQuery 1.9.1, but Kendo requires 1.8.2). Additionally, the kendo all JS file contains all of the scripts for the web, mobile, and dataviz frameworks.

Now that we have our references setup, let’s flesh out the UI. To begin, let’s setup the views and the layout, as the following:

<div id="newview" data-role="view" data-title="New Contact" 
  data-layout="viewlayout" data-model="newViewModel">
	.
	.
</div>

<div id="existingview" data-role="view" data-title="Existing Contacts" 
  data-layout="viewlayout" data-model="existingViewModel">
	.
	.
</div>

<div data-role="layout" data-id="viewlayout">
	<header data-role="header">
		<div data-role="navbar">
			<a class="nav-button" data-align="left" data-role="backbutton">Back</a>
			<span data-role="view-title"></span>
		</div>
	</header>

	<footer data-role="footer">

		<div id="footertabs" data-role="tabstrip">
			<a href="#newview" data-icon="add">New</a>
			<a href="#existingview" data-icon="contacts">Contacts</a>
		</div>

	</footer>
</div>

To begin, we have two views, a new view and an existing view. A view is the container for what the user sees, defined by a data-role value of “view”; the user only sees one view at a time, starting with the new view. A view has a header and footer. The header contains the header title bar, plus any buttons used for navigation. The footer bar contains additional footer options, which is a set of tabs to navigate between the two views. Notice that the header and footer are defined an element with a data-role attribute value of “layout”. Layouts are a convenient way to reuse the header and footer across all views. This layout above is used for the new and existing view. Now we have the views defined, and the navigation between views using the tabstrip component. But if you viewed this page in the browser, it wouldn’t be very useful. For instance, the tabscript would not work as it currently stands. We need to enable a JavaScript widget that Kendo uses to provide the tabbing feature. Kendo uses a JQuery UI widget-like capability for enabling these behaviors. For instance, to enable the tabstrip programmatically, one would do:

$("#footertabs").kendoMobileTabStrip({ /* options */ });

However, Kendo made this even easier through it’s application class; by adding the following line, the entire view is wired up to it’s related JavaScript widget, all linked together through the data-role attribute, and related “data-” configurations.

var kendoApp = new kendo.mobile.Application(document.body, {
	loading: "Loading..."
});

Now that our views are wired up and our components are linked to their JavaScript counterpart, the next task needing performed is to define the MVVM data models. Before we fully get into that, let’s look again at the complete view.

<div id="newview" data-role="view" data-title="New Contact" data-layout="viewlayout" data-model="newViewModel">
	<form action="" method="post">
		<ul id="newformlist" data-role="listview">
			<li>
				<label>Name:</label>
				<input type="text" id="Name" data-bind="value:newName" />
			</li>
			<li>
				<label>Suffix:</label>
				<input type="text" id="Suffix" name="Suffix" data-bind="value:newSuffix" />
			</li>
			<li>
				<label>Email:</label>
				<input type="email" id="Email" name="Email" data-bind="value:newEmail" />
			</li>
			<li>
				<label>Phone:</label>
				<input type="tel" id="Phone" name="Phone" data-bind="value:newPhone" />
			</li>
		</ul>
	</form>
</div>

<div id="existingview" data-role="view" data-title="Existing Contacts" data-layout="viewlayout" data-model="existingViewModel">
	<ul id="existinglist" data-role="listview" data-bind="source:contacts" data-template="contacttemplate">
	</ul>
</div>

Here we ahve our two views. The first container a form, and the last contains a list. Both use the listview component, a mobile-specific component that binds data similar to a grid, or can be used as shown above for representing a form. Both views define certain attributes; they define a title that will appear in the layout’s title bar. The views also define the layout to use (as we saw above) and the data model to bind to. Within eaach view is an HTML element that defines what to bind to. For instance, in our form, each textbox is bound, using the data-bind attribute, to some specified value (newName, newEmail, etc). The “value:” prefix specifies the type of bindings to use. There are quite a few bindings available; for know, now that the value binding links the value from the view model to the “value” attribute of the element. In future posts, I’ll talk about some of the other attributes available. These bindings link the model (newViewModel) to an attribute of that model. This makes it very easy to bind the data in a two-way fashion from some backend model to the user interface, and vice versa.

Our listview that displays a list of contacts defines a source, or the array of data to bind to, and specifies a template to use. Templates are script element defining the UI to define for the item of the list. The following is the attached template the listview uses to show the name, phone, and email for each contact. Note that templates use a #= # or #: # convention for binding, and can even accept javascript statements like the “if” statement below.

<script type="text/x-kendo-template" id="contacttemplate">
	<h3>
		#= Name#
		# if (Suffix != null && Suffix.length > 0) { #
			#= Suffix #
		# } #
	</h3>
	<div>
		#= Phone #
	</div>
	<div>
		#= Email #
	</div>
</script>

To wire up these views, we need some data. This is where the view models come into play. Kendo defines a view model using the observable method; note that this approach is different than what other MVVM frameworks use (like Knockout JS for one). Kendo transforms the basic model definition into an object with observable properties to provide the two-way binding.

var newViewModel = kendo.observable({
	newName: "ABC",
	
	newSuffix: "",
	
	newPhone: "",
	
	newEmail: ""
});

var existingViewModel = kendo.observable({
	contactsLoaded: true,
	
	contacts: [
		{ Name: "Ted Person", Suffix: "", Email: "ted.person@fake.com", Phone: "555-555-5555" },
		{ Name: "Amu Person", Suffix: null, Email: "amy.person@fake.com", Phone: "555-555-5555" },
		{ Name: "Bob Person", Suffix: "Jr", Email: "bob.person@fake.com", Phone: "555-555-5555" }
	]
});

And voila, this is all that you need to define multiple views, binding them to an MVVM model. I’ve created a JS fiddle with the scripts; it’s not fully working correctly, which is something I have to contact Telerik about. But you can get the contents and scripts here (which work great locally), or the full example here.

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.

Icenium: Mobile HTML 5 Development Offering from Telerik

If you have looked at Telerik’s product offering lately, you may have noticed a new listing for Icenium, a cross-platform hybrid mobile development solution.  Icenium is a toolset allowing developers to code applications using HTML 5, CSS, and JavaScript.  Using Apache Cordova (AKA PhoneGap), Icenium provides a common toolset and framework for developing applications.  It also includes and online and installable editor for developing such applications.  This framework has the ability to push the applications to many test devices at once, allowing for a USB deployment.  However, when it comes time to publish the application, Icenium uses a cloud environment for building the application in each environment (iOS, Android, etc.).

I’m really looking forward to see what Icenium has to offer, and if it is as good as it’s other products are, Icenium is going to be an excellent choice for mobile development.  You can read a more detailed introduction here: http://www.icenium.com/community/blog/icenium-team-blog/2012/10/22/introducing-icenium—an-integrated-cloud-environment-for-hybrid-mobile-app-development

Telerik Q3 2012: Gauge and PivotGrid

Some controls I was hoping Telerik would add for a long time appeared in the Q3 2012 release of the framework.  For the longest time that I can remember, Infragistics and other vendors had a gauge control for displaying certain benchmarks.  While gauges can be overused, some users like to see a gauge as it easily provides a meaningful representation of data representing the progression of numerical data (such as a completion percentage, a percentage of resources collected, etc).

The latest Telerik Q3 2012 framework has finally added this control.  I’m sure it’s not feature complete, but with any new control from Telerik, there will be many features to come that will make the gauge an excellent control.  View the demo here: http://demos.telerik.com/aspnet-ajax/gauge/examples/overview/defaultcs.aspx

The next control I’m glad to see it being offered, as it will benefit my organization personally, is a control that works like the Tablix in SSRS, but is now within Telerik’s ASP.NET AJAX framework: the PivotGrid control.  The PivotGrid provides a comprehensive analysis and aggregation of the data bound to it.  While in beta form, the control is very promising and I’m sure will greatly mature in next releases.  View the demo here: http://demos.telerik.com/aspnet-ajax/pivotgrid/examples/firstlook/defaultcs.aspx