Telerik blogs

In our Getting Start with Win8 HTML RadControls Part 1 post, I drilled into the different templates available for creating Windows 8 HTML apps, detailed adding the RadControls for Windows 8 HTML to an existing project, and used the Telerik supplied template to create a new Windows 8 HTML navigation app configured with the RadControls.  Now it’s time to sling some code!

Setting the Stage

The Telerik RadControls Windows 8 HTML Application template preloads the default page (home.html) with a RadCustomHubTile.  This is an awesome control, but to keep this post simple, I will clear out that control from the default page. Remove the code in Listing 1 so the <body> section looks like Listing 2. I will be adding our content inside the <section> with the “main” role.

<div data-win-control="Telerik.UI.RadCustomHubTile" data-win-options="{frontContentTemplate:select('#frontTemplate'),backContentTemplate:select('#backTemplate')}"> 
 <div id="frontTemplate"><div style="text-align:center">Add content Here!</div></div> 
 <div id="backTemplate"><div style="text-align:center">Telerik Navigation Application template.</div></div> 
</div>
Listing 1 – The RadCustomHubTile core code
<div class="fragment homepage"> 
 <header aria-label="Header content" role="banner"> 
 <button class="win-backbutton" aria-label="Back" disabled type="button"></button> 
 <h1 class="titlearea win-type-ellipsis"> 
 <span class="pagetitle">Welcome to TelerikNavigationApp!</span> 
 </h1> 
 </header> 
 <section aria-label="Main content" role="main"> 
 </section> 
</div>
Listing 2 – Home page <body> with RadCustomHubTile removed

Opening the Project in Blend

There are two ways to add controls to an HTML page – either typing the controls by hand or using Blend. I use Blend the majority of the time to add controls to my pages since the resulting code is the same as if I typed it, and it’s easier in Blend. To open your page in Blend, simply right click on home.html, and select Open in Blend (as in Figure 1).

image
Figure 1 – Opening html page in Blend

Adding a RadGrid

Once you have your project open in Blend (as shown in Figure 2), it’s very easy to add WinJS controls to your page.  On the left hand side under the “Assets” tab are all of the available controls, snippets, and media available to you.  Clicking on References –> RadControls for Windows 8 (#1) will show all of the RadControls.  Select the RadGrid (#2) and drag it onto the page (#3).

image
Figure 2 – Default.html opened in Blend

Using Blend to Set Options

In addition to easily adding controls to your page, Blend creates property pages for well written controls, and the RadControls take full advantage of this. To open up the property pages, click the control in the live DOM window (on the left) or click the element in the HTML editor (the window in the middle of the IDE).  Figure 3 shows the properties page for the HTML Attributes for the RadGrid I just added to the page. Updating values in the properties page will update the “data-win-options” values for the control. 

image

Figure 3 – RadGrid Properties Pages

Depending on the complexity of the option, I switch between Blend and Visual Studio to enter the values.

Keeping Visual Studio and Blend in Sync

This is the super easy part, since it happens automatically!  After adding the RadGrid through Blend and going back to Visual Studio, you will be greeted with the dialog similar to the one shown in Figure 4.

image
Figure 4 – File Changed notification dialog

This works bi-directionally – Visual Studio and Blend work very hard to stay in sync. The only time I have had an issue is when I edit files in both IDEs without saving my changes.  In that case, last one in wins. So just be sure to save early and often.

Adding Data to the Project

The databound RadControls are extremely flexible in where the data comes from.  In addition to static data (e.g. used in a RadComboBox to limit selection choice), data can be from a local file or webservice (as json or xml), added from a WinJS.Binding.List, or a Telerik.DataSource.

Static data hardcoded in the data-win-options doesn’t make much sense for a grid.  For this post I am going to use a local file to get the data, but the mechanism for getting the data from a webservice is exactly the same. The only difference is the URL used in the dataSource configuration.  For a webservice, the URL is (obviously) that of the web service.  For a local file, the url is the path to the file as it is in the project.  This is important, since the file structure gets changed once the project is compiled.  As developers we don’t need to care where the file ends up, since the compilation process will take care of making sure the URL is correctly updated.

Adding a JSON Local DataSource to the Project

To begin, add a new folder into your project called “data”.  This is not a requirement, it’s just a convention.  In this folder, add a new “Text File” from the “Add New Item” dialog.  Name this file “customers.json”. Open up the text file, and paste the data in from Listing 3.

{
  "customers": 
  [
    {"firstName":"Philip","lastName":"Japikse","age":44},
    {"firstName":"Fred","lastName":"Flinstone","age":35},
    {"firstName":"Barney","lastName":"Rubble","age":31},
    {"firstName":"Betty","lastName":"Rubble","age":22},
    {"firstName":"Wilma","lastName":"Flinstone","age":24},
    {"firstName":"BamBam","lastName":"Rubble","age":2},
    {"firstName":"Pebbles","lastName":"Flintstone","age":3},
    {"firstName":"Dino","lastName":"Flinstone","age":4},
    {"firstName":"Baby Puss","lastName":"Flinstone","age":4},
    {"firstName":"Hoppy","lastName":"Rubble","age":2},
    {"firstName":"Pearl","lastName":"Slaghoople","age":65},
    {"firstName":"Sam","lastName":"Slagheap","age":33},
    {"firstName":"Uncle Tex","lastName":"Hardrock","age":45},
    {"firstName":"Joe","lastName":"Rockhead","age":35},
    {"firstName":"Nate","lastName":"Slate","age":31}
  ]
}

Listing 3 – JSON Data for the Grid

NOTE: There is an add new item type called “Resources File (.resjson)”.  Do not use this, as it gets added to the project as a resource file and not a content file.  The RadGrid will not be able to use the data in this file.

Expected JSON Structure

As you can see from the sample, there is a root JSON object “customers” that contains a list of customer objects.  This is the expected top level data format.  There can be additional nodes underneath each level, which is beyond the scope of this post, but at a minimum there must be a root object.  The reason for this will become apparent when I add the data to the RadGrid. 

Adding the Data to the RadGrid

The data in the JSON file can be added to our RadGrid a number of ways. 

  • Through the data-win-options element in markup
  • Setting the options in the RadGrid constructor (if the RadGrid is added to the DOM through code and not markup)
  • Parsing the JSON into a
    • WinJS.Binding.List
    • Telerik.DataSource

The RadGrid is set to autobind by default, so all you need to do is set the dataSource property and the RadGrid does the rest.

Setting the DataSource in Markup

Listing 4 shows declaring the data source using the data-win-options attribute in markup.

<div id="testGrid" 
 data-win-control="Telerik.UI.RadGrid" 
 data-win-options='{
    dataSource: {
        transport: {
            read: {
                url: "/data/customers.txt",
                dataType: "json"
            }
        },
        schema: {
            data: "customers"
        },
    },
}'> 
</div>
Listing 4 – Setting the DataSource in Markup

Setting the DataSource in JavaScript

To set the DataSource in JavaScript, first change the HTML to remove the data-win-control attribute so there is only a <div> tag with the id of “testGrid” (as shown in Listing 5).

<div id="testGrid"> 
</div>

Listing 5 – Updated <div> tag for programmatic creation of the RadGrid

Now open the “home.js” file and replace the ready function with the code shown in Listing 6. Note that the syntax is exactly the same.  That’s because the value of the data-win-options attribute is passed into the constructor for the data-win-control.

ready: function (element, options) {
 var grid = new Telerik.UI.RadGrid(testGrid, {
        dataSource: {
            transport: {
                read: {
                    url: "/data/customers.txt",
                    dataType: "json"
                }
            },
            schema: {
                data: "customers"
            },
        },
    });
}

Listing 6 – Creating the RadGrid and setting the DataSource in JavaScript

NOTE: I am using one of my favorite IE10 Browser Quirks in this sample.  In short, the IDs of markup elements are added to the global namespace and can be reference in code without having to go through a query selector.

Breaking Down the Options

There are two main items under the “dataSource” that are set in the previous example, “transport” and “schema”.  Theres much more information in the Help Documentation on RadGrid Data binding.

Transport

The transport option defines the different mechanisms for CRUD operations.  I am only using the “read” option, but all of the usual types exist, including “add”, “remove”, and “update”. 

For the read property, the minimum that must be set is the “url” and the “dataType”.

Schema

There are multiple options for the “schema”, but the only one that I am using (and the minimum required) is the “data” tag.  It specifies the root JSON element that contains the collection to be loaded into the RadGrid.

The Result

Run the project, and voila! A grid with data.

image
Figure 5 – The RadGrid First Look

There are some improvements that are very simple to add to the RadGrid.

  • Update the column headers to be more readable
  • Add Sorting
  • Add Filtering
  • Add Grouping

Customizing RadGrid Headers 

By default, if no columns are specified in the options, the RadGrid will auto populate the columns based on the data.  The column headers are the field names, and all of the columns are brought in as strings. Changing the headers is as simple as adding the code shown in Listing 7 that defines the field/title pair. There are a lot more options available, including formatting and using templates.  More information can be found in the help documents.

columns: [
    {
        field: "firstName",
        title: "First Name",
    },
    {
        field: "lastName",
        title: "Last Name"
    },
    {
        field: "age",
        title: "Age",
    }
],

Listing 7 – Customizing the column headers

The resulting partial image of the grid is shown in Figure 6.

image
Figure 6 – Customized Columns

Allowing Sorting of Rows

Sorting is just as easy. Use the “sorting” property with one of the choices listed:

  • none – disables sorting for the RadGrid
  • single – single column sorting – click once for ascending, second click for descending
  • multiple – multiple column sorting
  • single, allowUnsort – single column sorting.  Third click removes the sorting from the column
  • multiple, allowUnsort – single column sorting.  Third click removes the sorting from the column

I chose

sortable: "multiple, allowUnsort",
 

Listing 8 – Enabling Sorting

image
Figure 7 – Sorted Records

For full details, please refer to the help documentation on sorting

Allowing Filtering

Filtering is enabled by adding a single property – “filterable”.  It is customizable as well, from selecting which columns can or cannot be filtered, to custom filtering. The single line of code is shown in Listing 9. NOTE: Since we did not specify the data type of the fields in the schema, all fields are strings. See this post for more information on Formatting Columns and Specifying Data Types.

filterable: true,

Listing 9 – Adding Filtering

Filterable columns are indicated by the funnel shown in the column header, and clicking it provides the user interface as shown in Figure 8. 
image

Figure 8 – Filtering

Please refer to the help documentation for the full information on RadGrid Filtering.

Allowing Grouping

Similar to sorting and filtering, basic grouping is very simple to add.  The necessary property is shown in Listing 10.

groupable: "enabled",
Listing 10 – Adding Grouping

Once grouping is enabled, the grid shows a grouping area on the left side as shown in Figure 9.  To group, drag column headers over to the grouping area.

image

Figure 9 – Grid with Filtering Enabled

After dragging the Last Name column over to the grouping area, the grid will show the data grouped as in Figure 10.

image

Figure 10 – Grouped by Last Name

The Complete Settings

The complete data-win-options configuration is shown in Listing 11.

<div id="testGrid" 
    data-win-control="Telerik.UI.RadGrid" 
    data-win-options='{
            dataSource: {
                transport: {
                    read: {
                        url: "/data/customers.txt",
                        dataType: "json"
                    }
                },
                schema: {
                    data: "customers",
                },
            },
            columns: [
                {
                    field: "firstName",
                    title: "First Name",
                },
                {
                    field: "lastName",
                    title: "Last Name"
                },
                {
                    field: "age",
                    title: "Age",
                }
            ],
            sortable: "multiple, allowUnsort",
            filterable: true,
            groupable: "enabled",
      }'>
</div>
Listing 11 – The complete Options Settings

Summary

Once you get your data source configure, creating an interactive grid is as easy as adding a few options.  As this post barely scratched the surface of what the RadGrid can do.  Try it for yourself.  Download the RadControls for Windows 8 HTML today. You’ll be amazed at the user interfaces you can create with just a few lines of code!


Japikse
About the Author

Phil Japikse

is an international speaker, a Microsoft MVP, ASPInsider, INETA Community Champion, MCSD, CSM/ CSP, and a passionate member of the developer community. Phil has been working with .Net since the first betas, developing software for over 20 years, and heavily involved in the agile community since 2005. Phil also hosts the Hallway Conversations podcast (www.hallwayconversations.com) and serves as the Lead Director for the Cincinnati .Net User’s Group (http://www.cinnug.org). You can follow Phil on twitter via www.twitter.com/skimedic, or read his personal blog at www.skimedic.com/blog.

 

Comments

Comments are disabled in preview mode.