Tips for implementing autocomplete in a textbox on an ASP.NET website with jQuery

Make sure to include a control named ProductType of type textbox in your .aspx page.

[WebMethod(EnableSession = true)]
    public static List<string> GetAutoCompleteDataProduct(string ProductType)
    {
        // string pid = "";
        ProductMasterBL objProductMasterBl = new ProductMasterBL();
        DataTable dtSearchProducts = objProductMasterBl.GetProductTypes(ProductType);
        List<string> result = new List<string>();
        for (int i = 0; i < dtSearchProducts.Rows.Count; i++)
        {
            result.Add(dtSearchProducts.Rows[i]["ProductName"].ToString());
        }
        if (result.Count == 0)
        {
            result.Add("No match found.");
        }
        return result;
    }

The corresponding code behind:

$(document).ready(function () {
SearchText();
});
function SearchText() {
   // var txtSearch = document.getElementById('txtProductType');
    $("#txtProductType").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Customers.aspx/GetAutoCompleteDataProduct",
                data: "{'ProductType':'" + request.term +"'}",
                dataType: "json",
                success: function (data) {
                    response(data.d);
                },
                error: function (result) {
                    alert("Error");
                },
                focus: function () {
                    // prevent value inserted on focus
                    return false;
                },
            });
        }
    });
}

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />

This block of code encompasses the code behind logic, JavaScript functions, and essential script links for functionality

Answer №1

To implement this feature, you can follow these steps:

Firstly, include the following code snippet in your project:

<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

Next, add the following controls to your .aspx file:

<asp:TextBox ID="textBox" runat="server" OnTextChanged="textBox_TextChanged" AutoPostBack="true" class="form-control"></asp:TextBox>
                    <cc1:AutoCompleteExtender ServiceMethod="SearchAutoComplete"
                        MinimumPrefixLength="1"
                        CompletionInterval="100" EnableCaching="False"
                        TargetControlID="textBox"
                        ID="AutoCompleteExtender1" runat="server" DelimiterCharacters="" Enabled="True" ServicePath="">
                    </cc1:AutoCompleteExtender>

Finally, add the following C# code snippet to handle the autocomplete functionality:

[System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static List<string> SearchAutoComplete(string prefixText, int count)
        {
            using (var _context = new Entities())
            {
                var Q = from lcN in _context.table                                     
                               where (lcN.Name.Contains(prefixText))
                               select lcN;
                List<String> list = new List<String>();
                foreach (var Qr in Q )
                {
                    List.Add(Qr.Q );
                }
                return list;
            }
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Organizing Dates in a Kendo Grid: How to Filter and Sort a DateTime Field

I am working with a datetime column in my Kendo Grid that displays values like this: 2014-04-11 12:43:41.720 To simplify the display, I have changed the template to show only short dates: 04/11/2014 The reason for not sending preformatted data to the col ...

Modifying a div element upon the successful completion of an ajax/json request

Currently, I have a form on my webpage for creating a new album. Alongside this form, there is also a delete album form. After successfully creating an album, I want to automatically update the checkbox list in the delete album form with the details of the ...

Display a modal across all pages by incorporating a button component, regardless of its placement

I've implemented a header in my react app with a show dialog button that appears on all necessary pages. Currently, my approach to displaying the dialog is as follows: When the user clicks the button, I dispatch an action to the redux store { type:S ...

Encountering issues with Next JS navigation when using the mobile back button

Recently, I put together a website using Next js 13 (with app router) and utilized Mantine UI for the front-end design. On mobile devices, I have implemented a responsive menu on the homepage. However, when I try to navigate back to the homepage from the ...

The problem of a static click function not working when clicked on a link. What is the solution for this

Details I am currently using a flickity slideshow that automatically goes to the next picture on a click. Within the slideshow, I have placed a button with text and a link to an external website (e.g. ). My Problem: When I click on the link, my slidesho ...

Is there a way to store div content in a PHP Session?

Just starting to learn php & ajax, so be patient with me. I have a clickable map. When the user clicks on a point, the value is displayed in a div. Once they select a point, they should be able to proceed to the next step. Now I want to save the content ...

Do I have to specify the protocol when loading jQuery?

Underneath is the code snippet: <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script> <script type="text/javascript"> console.log(jQuery); </script> This code works perfectl ...

Exploring connections between various objects using JavaScript

Currently, I am working with two sets of arrays: $scope.selectedEmployees = ["1001", "1002"]; $scope.selectedTasks = ["Task1", "Task2"]; My goal is to create an array of objects that combine employees and tasks in a many-to-many relationship. The length ...

Tally the number of items using the jQuery AJAX method and the

Extracting information from an XML DB looks something like this: <record> <eventname></eventname> <company></company> <city></city> <state></state> </record> The data is then parsed usi ...

Is it possible to retrieve the createdAt timestamp without displaying the 'GMT+0000 (Coordinated Universal Time)'?

After conducting an extensive search, I have yet to find a satisfactory answer. My goal is to configure it without including the CUT time. {name: "Registered:", value: `${user.createdAt}`}, {name: "Joined:", value: `${message.guild.joinedAt}`} Presently, ...

Decoding JSON data with JavaScript

My JavaScript code is giving me trouble. I am using an ajax method that returns a JSON string like this: { "ObjectResponse": { "Operation": "OK", "Response": "SUCCESS", "Message": "List of AAA Found", "List": [ { "keySourc ...

Populate an ng-repeat table again while maintaining its original sorting order

Incorporating a table filled with data fetched from a webservice using the ng-repeat directive, I have enabled sorting functionality for all columns. Additionally, at regular intervals, the application polls the webservice to retrieve updated data. This o ...

How can I retrieve a single row at a time using mysqli_fetch_array function?

In my PHP code, I have created a quiz to display one question and four multiple choices on an HTML page using AJAX and jQuery. While I know how to use a while loop to display all the questions at once, I am unsure of how to show only one question at a time ...

Tired of the premium content on Medium.com. How can I conceal premium posts that are aimed at a specific class within a parent element?

I have noticed that all Premium posts contain an element with the class ="svgIcon-use" <svg class="svgIcon-use" width="15" height="15" viewBox="0 0 15 15" style=""><path d="M7.438 2.324c.034-.099.090 123 0l1.2 3.53a.29.29 0 0 0 .26.19h3.884c.11 0 ...

Implementing a JavaScript validator for an ASP textbox

I have come across many posts discussing how to prevent an ASP textbox from accepting only numbers. However, I am looking for a JavaScript example that can check if the entered value falls between 0 and 100. My validator currently checks if each key entere ...

Selecting a single checkbox automatically selects all other checkboxes

Is there a way to automatically check all other checkboxes if one checkbox is checked? Here's the code snippet I have: <tr> <td class="small"><asp:CheckBox ID="chkReportModuleName" runat="server" name="report"></asp:CheckBox& ...

The function goes beyond just marking individual Todos as done, as it has the capability to mark all Todos as completed

As a beginner, I am facing an issue where all the items in my to-do list are marked as done when I try to mark just one. Can someone please help me understand what I am doing wrong? I have a function called handleDoneTask that is meant to mark each indivi ...

Creating a new nested object in JavaScript using the keys of the current object

What is the most efficient method for creating a new object based on the keys of the current object? Each key in the original object should correspond to a specific element in the new object - for example, activityName1 should match the first element' ...

Change to JSONArray using angularjs

Here is a json object: "values": [ {"name": "name1"}, {"name": "name2"}, {"name": "name3"} ] I want to convert it into this format: values: ["name1", "name2", "name3"]; Can this conversion be done in AngularJS or any other JavaScript functi ...

Is it possible to use a full-width material-ui Button inside a Badge component?

Within a grid, I had initially used fullWidth on a Button to make it expand and fill the container. Everything was functioning correctly until I enclosed the Button in a Badge element. Now, the fullWidth property is not being applied, and the button rever ...