DEV Community

Cover image for Google-Powered Autocomplete: Leveraging Search Suggestions in .NET MAUI
Jollen Moyani for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

Google-Powered Autocomplete: Leveraging Search Suggestions in .NET MAUI

In this walkthrough, we will explore the custom filtering support provided by Syncfusion’s Autocomplete control. The Autocomplete control was designed to give users possible matches as they type, and it comes with a range of features such as different suggestion modes and custom search.

Using the custom filter support, we can create a Google search experience where suggestions are filtered based on user input.

This blog will guide you through the steps to achieve this behavior. By implementing this custom filtering feature, you can provide your users with more accurate and relevant search suggestions that enhance their overall experience. So, let’s learn how to utilize this feature of Autocomplete control in a .NET MAUI app.

How to add the Syncfusion control

First, we’ll incorporate the Autocomplete control and associate data with it.

Step 1: Add the .NET MAUI Autocomplete reference

Syncfusion’s .NET MAUI controls are available on NuGet.org. To add the .NET MAUI Autocomplete to your project, open the NuGet package manager in Visual Studio, search for Syncfusion.Maui.Inputs , and then install it.

Step 2: Handler registration

In the MauiProgram.cs file , register the handler for the Syncfusion core.

using Microsoft.Extensions.Logging;

using Syncfusion.Maui.Core.Hosting;

namespace GoogleSearchDemo;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
    var builder = MauiApp.CreateBuilder();
    builder
      .ConfigureSyncfusionCore()
      .UseMauiApp<App>()
      .ConfigureFonts(fonts =>
      {
         fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
         fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
      });

          #if DEBUG
      builder.Logging.AddDebug();
          #endif
      return builder.Build();
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Include the namespace

After adding the NuGet package to the project, as discussed in the previous reference section, add the XML namespace to the MainPage.xaml file, as shown in the following code example.

xmlns:editors="clr-namespace:Syncfusion.Maui.Inputs;assembly=Syncfusion.Maui.Inputs"
Enter fullscreen mode Exit fullscreen mode

Step 4: Add the Autocomplete control

Add the Autocomplete control inside a grid. Also, customize the Autocomplete control with these properties:

  • Placeholder: Displays a text hint inside the control before the user inputs any value.
  • MaxDropDownHeight : Maximum height of the dropdown list that appears when it gets opened.
  • TextSearchMode: Sets the search mode for matching items in the Autocomplete control’s data source. This property is set to Contains , meaning the control will show all items containing the typed text.
  • WidthRequest and HeightRequest : These properties set the preferred width and height of the control.
<Grid Margin="0,20,0,0">
 <editors:SfAutocomplete HeightRequest="50"
                         Placeholder="Search something" MaxDropDownHeight="250"
                         TextSearchMode="Contains"
                         WidthRequest="300">
 </editors:SfAutocomplete>
</Grid>
Enter fullscreen mode Exit fullscreen mode

Step 5: Set custom filtering class

The Autocomplete control supports applying custom filter logic to suggest items based on your filter criteria using the FilterBehavior and SearchBehavior properties. The default value of FilterBehavior and SearchBehavior is null. Here, the FilterBehavior is set to CustomFiltering. Creation of the CustomFiltering class is explained in the upcoming section.

<Grid Margin="0,20,0,0">
 <editors:SfAutocomplete HeightRequest="50"
                         Placeholder="Search something" MaxDropDownHeight="250"
                         TextSearchMode="Contains"
                         WidthRequest="300">
  <editors:SfAutocomplete.FilterBehavior>
   <local:CustomFiltering/>
  </editors:SfAutocomplete.FilterBehavior>
 </editors:SfAutocomplete>
</Grid>
Enter fullscreen mode Exit fullscreen mode

With this, the UI part is completely implemented. Let’s focus on the backend where the CustomFiltering class is implemented.

Creating the CustomFiltering class

Next, let’s create a Google-like suggestion filter using the custom filter property of the .NET MAUI Autocomplete control.

Step 1: Create a custom class

Create a class named CustomFiltering and import the Syncfusion.Maui.Inputs namespace, which provides classes and interfaces for the Autocomplete control.

using Syncfusion.Maui.Inputs;
using System.Xml.Linq;

namespace GoogleSearchDemo
{
    public class CustomFiltering
    {
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Implement the interface

Implement the interface IAutocompleteFilterBehavior in the CustomFiltering class. This interface defines the filtering behavior for the control. The first step is to import the necessary namespaces required for the code to execute.

using Syncfusion.Maui.Inputs;
using System.Xml.Linq;

namespace GoogleSearchDemo : IAutocompleteFilterBehavior
{
    public class CustomFiltering
    {
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Customize the constructor method

Define a constructor method, which is called when an instance of the CustomFiltering class is created. In the constructor, call the GetGoogleSuggestions method with the initial search term test.

using Syncfusion.Maui.Inputs;
using System.Xml.Linq;

namespace GoogleSearchDemo
{
    public class CustomFiltering : IAutocompleteFilterBehavior
    {
        public CustomFiltering()
        {
            GetGoogleSuggestions("test");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Define the filtering method from IAutocompleteFilterBehavior

Define the GetMatchingItemsAsync method, which is responsible for filtering the data for the Autocomplete control. It takes two arguments: the SfAutocomplete class’s source object and an instance of the AutocompleteFilterInfo class. The AutocompleteFilterInfo class contains the current filter text entered by the user.

using Syncfusion.Maui.Inputs;
using System.Xml.Linq;

namespace GoogleSearchDemo
{
    public class CustomFiltering : IAutocompleteFilterBehavior
    {
        public CustomFiltering()
        {
            GetGoogleSuggestions("test");
        }

        public Task<object> GetMatchingItemsAsync(SfAutocomplete source, AutocompleteFilterInfo filterInfo)
        {
            return GetGoogleSuggestions(filterInfo.Text);
        }

    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Define a method to get Google suggestions

Define a private, asynchronous method named GetGoogleSuggestions, which makes a web request to the Google search suggestions API to fetch suggestions for the given query.

It takes a string parameter query as input and returns a list of suggestions as an object. It uses the HttpClient class to make the web request and parses the XML response to extract the suggestions.

using Syncfusion.Maui.Inputs;
using System.Xml.Linq;

namespace GoogleSearchDemo
{
    public class CustomFiltering : IAutocompleteFilterBehavior
    {
        public CustomFiltering()
        {
            GetGoogleSuggestions("test");
        }

        public Task<object> GetMatchingItemsAsync(SfAutocomplete source, AutocompleteFilterInfo filterInfo)
        {
            return GetGoogleSuggestions(filterInfo.Text);
        }

        private async Task<object> GetGoogleSuggestions(string query)
        {
            if (string.IsNullOrEmpty(query) || string.IsNullOrWhiteSpace(query))
            {
                return new List<string>();
            }

            string xmlSuggestions;

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var searchQuery = String.Format("https://www.google.com/complete/search?output=toolbar&q={0}", query);
                    xmlSuggestions = await client.GetStringAsync(searchQuery);
                }
                catch
                {
                    return null;
                }
            }

            XDocument doc = XDocument.Parse(xmlSuggestions);
            var suggestions = doc.Descendants("CompleteSuggestion")
                                 .Select(
                                    item => item.Element("suggestion").Attribute("data").Value);

            return suggestions.ToList();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output suggestions similar to those found on Google

Output suggestions similar to those found on Google

GitHub reference

For more information, refer to the demo on GitHub.

Conclusion

Thank you for taking the time to read this blog post. In this article, we have discussed the necessary steps to display Google search suggestions in our .NET MAUI Autocomplete control with custom filtering support. We recommend exploring the Getting Started documentation. We hope you found this information helpful.

If you are an existing Syncfusion customer, the new version of Essential Studio is available for download from the License and Downloads page. For those who are not yet Syncfusion customers, we offer a 30-day free trial to explore our available features.

Please let us know in the comments section below if you have any specific feature requests for our .NET MAUI controls. Additionally, you can contact us for assistance through our support forums, support portal, or feedback portal. We are always happy to help you!

Related blogs

Top comments (0)