Building a search interface for local indexes in MVC

To perform searches based on locally stored search indexes on MVC sites, use the API from the CMS.Search namespace (provided as part of the Kentico.Libraries NuGet package).

  1. Prepare a SearchParameters object with the required search inputs and parameters.
  2. Call the SearchHelper.Search method.

    Example
                IEnumerable<string> searchIndexes = new List<string> { "ProductIndex", "ArticleIndex" };
                int pageNumber = 1;
                int pageSize = 10;
                UserInfo searchUser = MembershipContext.AuthenticatedUser;
                string cultureCode = "en-us";
                bool combineWithDefaultCulture = true;
     
                SearchParameters searchParameters = SearchParameters.PrepareForPages("search query", searchIndexes, pageNumber, pageSize, searchUser, cultureCode, combineWithDefaultCulture);
     
                SearchResult searchResult = SearchHelper.Search(searchParameters);
    

The Search method returns a SearchResult object representing the set of results. The result's Items property contains a collection of SearchResultItem objects, representing individual search results.

Every item provides properties corresponding to general search result fields (such as the title, image or content fields), as well as a Data property. The Data property is of an abstract BaseInfo type, and its run-time type depends on the searched Kentico object. For example:

  • If the search indexes pages, the run-time type of a search result item's Data property is of the TreeNode class. If you generated classes for your page types, the run-time type is of the generated class.
  • If the search indexes pages representing products, the run-time type of a search result item's Data property is of the SKUTreeNode class.
  • If the search indexes users, the run-time type of a search result item's Data property is of the UserInfo class.

You can use the Data property to access any object-specific values of the searched items.

Example – Building a search interface on MVC sites

The following search example uses an index that indexes pages (TreeNode objects) and products (SKUTreeNode objects). The example does not use pagination when displaying search result items.

  1. Open your MVC project in Visual Studio.
  2. Create a new model class for working with search queries and search result items.

    using System.Collections.Generic;
    using CMS.Search;

        public class SearchResultModel
        {
            public string Query { get; set; }
            
            public IEnumerable<SearchResultItem> Items { get; set; }
        }
    

  3. Create a controller with an action that searches and provides search results.

    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
     
    using CMS.Membership;
    using CMS.Search;
    
            // Adds the smart search indexes that will be used to perform searches
            public static readonly string[] searchIndexes = new string[] { "MVCSite.Index" };
            // Sets the limit of items per page of search results
            private const int PAGE_SIZE = 10;
     
            /// <summary>
            /// Performs a search and displays its result.
            /// </summary>
            [ValidateInput(false)]
            public ActionResult SearchIndex(string searchText)
            {
                // Displays the search page without any search results if the query is empty
                if (String.IsNullOrWhiteSpace(searchText))
                {
                    // Creates a model representing empty search results
                    SearchResultModel emptyModel = new SearchResultModel
                    {
                        Items = new List<SearchResultItem>(),
                        Query = String.Empty
                    };
     
                    return View(emptyModel);
                }
     
                // Searches the specified index and gets the matching results
                SearchParameters searchParameters = SearchParameters.PrepareForPages(searchText, searchIndexes, 1, PAGE_SIZE, MembershipContext.AuthenticatedUser, "en-us", true);
                SearchResult searchResult = SearchHelper.Search(searchParameters);
                
                // Creates a model with the search result items
                SearchResultModel model = new SearchResultModel
                {
                    Items = searchResult.Items,
                    Query = searchText
                };            
     
                return View(model);
            }
    

  4. Add a search input field to one of your site's views. For example:

    @using (Html.BeginForm("SearchIndex", "Search", FormMethod.Get))
    {
        <input type="text" name="searchtext" placeholder="Search..." maxlength="1000">
        <input type="submit" value="Search">
    }
    

  5. Create a view that displays the search result items provided by your search controller. For example:

    @model SearchResultModel
     
    @using CMS.Search;
     
    @if (!Model.Items.Any())
    {
        if (!String.IsNullOrWhiteSpace(Model.Query))
        {
            <h3>No results found for "@Model.Query"</h3>
        }
    }
    else
    {
        <h3>Results for "@Model.Query"</h3>
        foreach (SearchResultItem item in Model.Items)
        {
        <div>
            <strong>@item.Title</strong>
        </div>
        <div>
            @Html.Kentico().ResolveUrls(item.Content)
        </div>
        }
    }
    

Your visitors can now search on your website through the created search field. The system searches through the specified indexes and displays the results.


Was this page helpful?