简体   繁体   English

Asp.net MVC 中的自动完成文本框

[英]Autocomplete Text box in Asp.net MVC

I am working in asp.net MVC.我在 asp.net MVC 工作。 I need a text box to autocomplete by ajax function.我需要一个文本框来通过 ajax 函数自动完成。 Ajax function can't call values from the controller. Ajax 函数无法从控制器调用值。

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

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:您的控制器应以 JSON 格式响应数据,例如:

[{"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.您的 JSON 应该是动态的,否则,它会响应您相同的 JSON。 You should filter your data in your controller before responding back to the AJAX and the data always in the JSON format.在响应 AJAX 之前,您应该在控制器中过滤数据,并且数据始终采用 JSON 格式。

You can find more about autocomplete on https://jqueryui.com/autocomplete/ & https://jqueryui.com/autocomplete/#remote-with-cache您可以在https://jqueryui.com/autocomplete/https://jqueryui.com/autocomplete/#remote-with-cache上找到有关自动完成的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM