Google-Powered Autocomplete: Leveraging Search Suggestions in .NET MAUI
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (172).NET Core  (29).NET MAUI  (192)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (209)BoldSign  (12)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (63)Flutter  (131)JavaScript  (219)Microsoft  (118)PDF  (80)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (882)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (49)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (125)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (62)Development  (613)Doc  (7)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (37)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (488)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (41)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (368)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (30)Visual Studio Code  (17)Web  (577)What's new  (313)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Google-Powered Autocomplete Leveraging Search Suggestions in .NET MAUI

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(); } }

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"

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>

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>

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
    {
    }
}

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
    {
    }
}

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");
        }
    }
}

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);
        }

    }
}

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();
        }
    }
}
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.

Test Flight
App Center Badge
Google Play Store Badge
Microsoft Badge
Github Store Badge

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed
Scroll To Top