Google like dropdown search populated from database in Asp.Net

1.5k views Asked by At

I am looking for a simple but effective way to create a drop down search box which should work like the google search and is populated by values from a database which acts when I type anything in the textbox. I Should be able to select any of the values. I am looking for the simplest solution and do not want to use a web service or the ajax control toolkit like every example I have seen does. Any help would be greatly appreciated..

1

There are 1 answers

11
Steven Lemmens On

You're looking for something like JQuery's Autocomplete, found here: https://jqueryui.com/autocomplete/

If you don't want to use an AJAX query to do the search, you can include all data in your HTML if you want. I wouldn't advise it though, as that information is also publicly visible for your visitors if they take a look at your source. If that's not a problem, then by all means, take this route.

If you do want to load the data via AJAX, the Autocomplete I linked to can also work against a remote datasource. The documentation for that is here: https://jqueryui.com/autocomplete/#remote

Example without using a remote datasource (no ajax):

$(function() {
var availableTags = [
  "ActionScript",
  "AppleScript",
  "Asp",
  "BASIC",
  "C",
  "C++",
  "Clojure",
  "COBOL",
  "ColdFusion",
  "Erlang",
  "Fortran",
  "Groovy",
  "Haskell",
  "Java",
  "JavaScript",
  "Lisp",
  "Perl",
  "PHP",
  "Python",
  "Ruby",
  "Scala",
  "Scheme"
];
$( "#birds" ).autocomplete({
  source: availableTags
});

In this example you would have to think of a way to print all of your tags into the HTML above, because you obviously cannot hardcode this. How to do this, depends on the technology you're running on. (MVC, WebForms, ...). But you would generally just get all the tags from the database, and print them out into the javascript. Post back if you need an example of this and tell me your technology, and I'll update my answer.

example of remote datasource (with ajax):

$( "#birds" ).autocomplete({
  source: "/api/GetValuesForAutocomplete", //the url to query 
  minLength: 2 //the amount of letters the user has to type before the search begins
});

 //in your HTML you would have: 
<input id="birds" />

You'll find more complete examples on their website. The URL that you'll have to use for such an ajax query depends on what technology your website is written in. Do you have access to a WEB API project? Or is it an MVC website? Or a Webforms website?