Adding a Search Results item template

This topic shows how to enable a user to search for information within your app by using the Search Results item template included with Visual Studio. The item template for search enables an app to present a search results page for a search that's initiated from the WinJS.UI.SearchBox control. For descriptions of the item templates, see JavaScript item templates. For most apps, you can use item templates included with Microsoft Visual Studio 2013 to simplify your app development.

The Search Results template is a page control that implements the recommended navigation model for Windows Store apps. The Hub, Grid, Split, and Navigation project templates implement this navigation model. For more info, see the "Navigation model" section of the JavaScript project templates topic.

Important  To use the Search Results item template with the Navigation or Blank project template, you have to add additional project files. See the list that follows.

For more info and other ways to implement search, see QuickStart: Adding search.

The procedures in this topic show how to add the Search Results item template to the Hub, Grid, and Split templates. To add the item template to a different project template, please note the following:

  • For the Blank template, add the navigator.js file to your project. (You can find this file in another project template such as the Grid template.) In default.html, you must also add code to host content. For more info, see Navigation model.
  • For the Navigation and Blank template, add data.js to your project (you can find it in another project template such as the Grid template) or implement your own method to access data.
  • For the Navigation and Blank templates, add the search control and its event handlers in the home page for the template. For the Navigation template, the home page is home.html. For the Blank template, you must create your own home page or use default.html.

Add the Search Results item template

The following procedure shows how to add the Search Results item template to a project template.

Hh923025.wedge(en-us,WIN.10).gifTo add the Search Results item template

  1. Create a new project in Visual Studio. For this example, use either the Hub, Grid, or Split template.

  2. In the pages project folder of Solution Explorer, add a new folder named search.

  3. Open the shortcut menu for the search folder, and then choose Add > New Item.

  4. In the center pane of the Add New Item dialog box, choose Search Results Page. For this example, keep the default name, searchResults.html, that appears in the Name box.

  5. Choose Add.

    Visual Studio adds searchResults.html, searchResults.css, and searchResults.js to the project in the new search folder.

  6. Open searchResults.js and verify that the URI for the search page is correct,

    var searchPageURI = "/pages/search/searchResults.html";
    

    If you don't put the search files in the search folder, you'll need to update the URI.

  7. Open searchResults.html and verify that the reference to searchResults.css is correct.

    <link href="/pages/search/searchResults.css" rel="stylesheet" />
    

Add the search control (Hub template)

Use the WinJS.UI.SearchBox control to enable the user to search your app for data. These steps are different for each project template. These instructions apply to the Hub template. To use the Grid or Split template, see the next section, Add the search control (Grid or Split template).

Tip  This example shows one place to put the SearchBox control. If you want to display the search box in an app bar, put it in a top app bar. Otherwise, you may want to put a search box on each page of your app.

Hh923025.wedge(en-us,WIN.10).gifTo add the search control to the page

  1. In the home page of the app (hub.html), add the SearchBoxcontrol to the HEADER element.

    <h1 class="titlearea win-type-ellipsis">
        <span class="pagetitle">vsu_hub_windows_search</span>
    </h1>
    <div class="searchBox" data-win-control="WinJS.UI.SearchBox">
    </div>
    
  2. In the CSS file for the home page (hub.css), specify display properties for the SearchBox control. You can include the following CSS code after the rules for the first hub section.

    .hubpage header[role=banner] {
        position: relative;
        z-index: 2;
    }
    
    .hubpage header[role=banner] .searchBox {
        margin-left: 850px;
        margin-top: 70px;
    }
    
  3. In the JavaScript file for the home page (hub.js), create an event listener for the onquerysubmitted event. The handler captures queries from the SearchBox control.

    Create the listener in the ready function where the code comments indicate that you need to add initialization code.

    // TODO: Initialize the hub sections here.
    var elem = document.querySelector(".searchBox");
    elem.addEventListener("querysubmitted", this.searchHandler.bind(this));
    
  4. In hub.js, add the event handler to navigate to the search results page. Add the event handler in the same scope as the ready function.

    Important  Remove the comma from the code below if it is the last function that you define for the page.

    searchHandler: function (args) {
        WinJS.Navigation.navigate('/pages/search/searchResults.html', args.detail);
    },
    

    Tip  In the preceding code, the detail property of the event arguments contains information about the query, such as the query text.

  5. To continue with the Hub template, skip the next section and see Provide navigation to the items returned by search.

Add the search control (Grid and Split template)

Use the WinJS.UI.SearchBox control to enable the user to search your app for data. These steps are different for each project template. These instructions apply to the Grid and Split templates.

Tip  This example shows one place to put the SearchBox control. If you want to display the search box in an app bar, put it in a top app bar. Otherwise, you may want to put a search box on each page of your app.

Hh923025.wedge(en-us,WIN.10).gifTo add the search control to the page

  1. In the home page of the app (groupedItems.html in Grid and items.html in Split), add the SearchBox control.

    Place the control after the SECTION element for the ListView control, within the DIV element for the page fragment (with a class name of fragment groupeditemspage or fragment itemspage). The code shown here is for the Grid template.

    <section aria-label="Main content" role="main">
        <div class="groupeditemslist win-selectionstylefilled" aria-label="List of groups" data-win-control="WinJS.UI.ListView" data-win-options="{
                layout: {type: WinJS.UI.GridLayout, groupHeaderPosition: 'top'},
                selectionMode: 'none',
                currentItem: {type: WinJS.UI.ObjectType.item, index: 0, hasFocus: true},
                groupDataSource: Data.groups.dataSource,
                groupHeaderTemplate: select('.headertemplate'),
                itemDataSource: Data.items.dataSource,
                itemTemplate: select('.itemtemplate'),
                ongroupheaderinvoked: select('.pagecontrol').winControl.groupHeaderInvoked,
                oniteminvoked: select('.pagecontrol').winControl.itemInvoked
            }">
        </div>
    <div class="searchBox" data-win-control="WinJS.UI.SearchBox" >
    </div>
    
  2. In the CSS file for the home page (groupedItems.css or items.css), specify display properties for the SearchBox control. Add the following CSS at the beginning of the CSS file. (After testing, adjust the margin-left value to display the search control to the right of the app title.)

    Tip  For the Split template CSS code, use the .itemspage rule instead of .groupeditemspage.

    .groupeditemspage .searchBox {
        margin-left: 600px;
        margin-top: 70px;
    }
    
  3. In the JavaScript file for the home page (groupedItems.js or items.js), create an event listener for the onquerysubmitted event. The handler captures queries from the SearchBox control.

    Create the event listener in the ready function.

    var elem = document.querySelector(".searchBox");
    elem.addEventListener("querysubmitted", this._searchHandler.bind(this));
    
  4. In groupedItems.js or items.js, add the event handler to navigate to the search results page. Add the event handler in the same scope as the ready function:

    Important  Remove the comma from the code below if it is the last function that you define for the page.

    _searchHandler: function (args) {
        WinJS.Navigation.navigate('/pages/search/searchResults.html', args.detail);
    },
    

    In the preceding code, the detail property of the event arguments contains information about the query, such as the query text.

In this section, we modify the Search Results item template to support navigation. The Search Results item template code handles the search itself. You can modify its default behavior. For example, you may want to modify the _searchData function to match different kinds of app data. By default, the template compares titles and subtitles in the data model to the query string. In this example, we leave the search criteria unmodified.

Caution  The _searchData function looks for data provided by data.js. If you're using the Navigation or Blank template, you must either add data.js to your project or provide a method for searching your own data and then customize the _searchData function. For more info about the data model in data.js, see Adding data to a project template.

In this example, we implement code that provides navigation to the items that are returned by the search query and appear in the search results page.

Hh923025.wedge(en-us,WIN.10).gifTo add navigation to items

  1. Open searchResults.js and add code to the _itemInvoked function to navigate to the correct page. This code supports navigation from the search results page to the item page associated with a search result.

    Caution  The URI shown here is for the Hub template. For the Grid template, the URI must be: /pages/itemDetail/itemDetail.html. For the Split template, the URL must be: /pages/items/items.html.

    _itemInvoked: function (args) {
        args.detail.itemPromise.done(function itemInvoked(item) {
            // TODO: Navigate to the item that was invoked.
            var itemData = [item.groupKey, item.data.title];
            WinJS.Navigation.navigate("/pages/item/item.html", { item: itemData });
        });
    },
    
  2. In data.js, modify some values to make the search results easy to verify when you run the app. In this example, replace a few titles and subtitles in the sample data (the sampleItems variable) with "Hello" and "hloTitle", as follows:

    var sampleItems = [
        // . . .
        { group: sampleGroups[0], title: "Hello", subtitle: "Item Subtitle: 5", description:
            itemDescription, content: itemContent, backgroundImage: mediumGray },
        // . . .
        { group: sampleGroups[1], title: "hloTitle", subtitle: "Hello", description:
            itemDescription, content: itemContent, backgroundImage: darkGray },
        { group: sampleGroups[1], title: "Hello Again", subtitle: "Item Subtitle: 2", description:
            itemDescription, content: itemContent, backgroundImage: mediumGray },
        // . . .
    ];
    

Hh923025.wedge(en-us,WIN.10).gifTo test search

  1. Choose Local Machine from the drop-down list next to the Start Debugging button on the debugger toolbar.

  2. Choose F5 to start debugging.

  3. In the search box that appears in the left hub section, specify Hello, and press Enter.

    The search results page shows results from your data model that include the search term. This illustration shows the search results page when you enter "Hello" in the search box.

    Search results page

  4. Click one of the search results.

  5. The Hub, Grid, or Split app opens the items page with the selected title showing at the top.

    You can use the Back button to get back to the search results page.

JavaScript project templates for Windows Store apps

JavaScript item templates for Windows Store apps

Adding a Search Contract item template