M.Fazal
M.Fazal

Reputation: 93

Autocomplete Text box in Asp.net MVC

I am working in asp.net MVC. I need a text box to autocomplete by ajax function. Ajax function can't call values from the controller.

Here is the code:

 $( "#birds" ).autocomplete({
      source: function( request, response ) {
        $.ajax( {
          url: "search.php",
          dataType: "jsonp",
          data: {
            term: request.term
          },
          success: function( data ) {
            response( data );
          }
        } );
      },
      minLength: 2,
      select: function( event, ui ) {
        log( "Selected: " + ui.item.value + " aka " + ui.item.id );
      }
} );

Upvotes: 2

Views: 618

Answers (1)

Shahroz Khan
Shahroz Khan

Reputation: 638

Here is the complete code:

    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        $( function() {
            var cache = {};
            $( "#birds" ).autocomplete({
                minLength: 2,
                source: function( request, response ) {
                    var term = request.term;
                    if ( term in cache ) {
                        response( cache[ term ] );
                        return;
                    }

                    $.getJSON( "Your Controller URL", request, function( data, status, xhr ) {
                        cache[ term ] = data;
                        response( data );
                    });
                }
            });
        } );
    </script>

Your Controller should response the data in JSON format like:

[{"id":"Locustella naevia","label":"Common Grasshopper Warbler","value":"Common Grasshopper Warbler"},{"id":"Locustella certhiola","label":"Pallas`s Grasshopper Warbler","value":"Pallas`s Grasshopper Warbler"}]

Your JSON should be dynamic, otherwise, it will respond you the same JSON. You should filter your data in your controller before responding back to the AJAX and the data always in the JSON format.

You can find more about autocomplete on https://jqueryui.com/autocomplete/ & https://jqueryui.com/autocomplete/#remote-with-cache

Upvotes: 2

Related Questions