【问题标题】:Autocomplete Text box in Asp.net MVCAsp.net MVC 中的自动完成文本框
【发布时间】:2020-05-07 06:21:31
【问题描述】:

我在 asp.net MVC 中工作。我需要一个文本框来通过 ajax 函数自动完成。 Ajax 函数不能从控制器调用值。

代码如下:

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

【问题讨论】:

  • 请发布您的代码
  • Ajax 函数可以从控制器获取值

标签: asp.net ajax asp.net-mvc autocomplete


【解决方案1】:

完整代码如下:

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

您的控制器应该以 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"}]

您的 JSON 应该是动态的,否则,它会以相同的 JSON 响应您。您应该在响应 AJAX 之前过滤控制器中的数据,并且数据始终采用 JSON 格式。

您可以在https://jqueryui.com/autocomplete/ 上找到有关自动完成功能的更多信息 &https://jqueryui.com/autocomplete/#remote-with-cache

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 2018-09-21
    • 2017-08-26
    • 2019-03-25
    • 1970-01-01
    相关资源
    最近更新 更多