JQuery插件之Autocomplete

        JQuery插件真是太多了,今天来说下Autocomplete。大家都有用过Baidu,Google,都已体验过Autocomplete了。我们在Asp.net 也可以实现累似的效果。
使用jQuery plugin: Autocomplete,此处我使用的是Asp.net webform,当然你也可以使用Asp.net MVC。在MVC中,我们使用Controller/Action 返回数
据,在Asp.net webform 使用Handler即可。

        我们先来实现一个DataHandler,看Code,这里使用LinqToSQL做数据源。

   1:      /// <summary>
   2:      /// Summary description for ProductHandler
   3:      /// </summary>
   4:      /// <remarks>author Petter Liu http://wintersun.cnblogs.com </remarks>
   5:      [WebService(Namespace = "http://tempuri.org/")]
   6:      [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
   7:      public class ProductHandler : IHttpHandler
   8:      {
   9:          #region Properties (1) 
  10:   
  11:          /// <summary>
  12:          /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
  13:          /// </summary>
  14:          /// <value></value>
  15:          /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
  16:          /// </returns>
  17:          public bool IsReusable
  18:          {
  19:              get
  20:              {
  21:                  return false;
  22:              }
  23:          }
  24:   
  25:          #endregion Properties 
  26:   
  27:          #region Methods (2) 
  28:   
  29:          // Public Methods (2) 
  30:   
  31:          /// <summary>
  32:          /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
  33:          /// </summary>
  34:          /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
  35:          public void ProcessRequest(HttpContext context)
  36:          {
  37:              string querystr = context.Request.Params["q"];
  38:              context.Response.ContentType = "application/json";
  39:              context.Response.Write(SearchProduct(querystr));
  40:          }
  41:   
  42:          /// <summary>
  43:          /// Searches the product.
  44:          /// </summary>
  45:          /// <param name="keywords">The keywords.</param>
  46:          /// <returns>product string list</returns>
  47:          /// <remarks>author Petter Liu  http://wintersun.cnblogs.com </remarks>
  48:          public string SearchProduct(string keywords)
  49:          {
  50:              if (string.IsNullOrEmpty(keywords))
  51:                  return null;
  52:   
  53:             var productRepository = new Repository<Product>();
  54:             var result = productRepository.GetAll().Where(p => p.Name.Contains(keywords));
  55:   
  56:             var sbresult = new StringBuilder(result.Count());
  57:              foreach (Product p in result)
  58:              {
  59:                  sbresult.Append(p.Name);
  60:                  sbresult.Append("|");
  61:                  sbresult.Append(p.ProductNumber);
  62:                  sbresult.Append("\n");
  63:              }
  64:              return sbresult.ToString();
  65:          }
  66:   
  67:          #endregion Methods 
  68:      }


注意这里我们填充数据的时,返回了两个列(id,name),用”|”分隔,你可以查看autocomplete.js源码parse部分,你将会更清楚为什么这么做。

然后在新建一个html,在head处增加:

   1:      <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.3.2.min.js"></script>
   2:   
   3:      <script src="Javascripts/Plugins/jquery.autocomplete.js" type="text/javascript"></script>
   4:   
   5:      <link href="Themes/Default/main.css" rel="stylesheet" type="text/css" />
   6:      <link href="Themes/Default/jquery.autocomplete.css" rel="stylesheet" type="text/css" />


注意我这里使用 Microsoft Ajax Content Delivery Network ,非常的方便。具体使用方法,可参考Microsoft Ajax Content Delivery Network

然后在写加载时的Javascript:

   1:  $(document).ready(function() {
   2:          $("#productname").autocomplete("ProductHandler.ashx", {
   3:              width: 500,
   4:              max: 50,
   5:              minChars: 2,
   6:              cacheLength: 20,
   7:              delay: 150,
   8:              matchContains: true,
   9:              autoFill: false,
  10:              scrollHeight: 300,
  11:              formatItem: function(row, i, max) {
  12:                  return i + "/" + max + ": " + row[0];
  13:              },
  14:              formatMatch: function(row, i, max) {
  15:                  return row[0] + " " + row[1];
  16:              }
  17:              //            ,formatResult: function(row) {
  18:              //                return 'ProductName: ' + row[0] + "ProductNumber: " + row[1];
  19:              //            }
  20:          }).result(function(event, data, formatted) {
  21:              $('#productnumber').val(data[1]);
  22:              $("#selectresult").html(!data ? "No match!" : "You have selected: " + formatted);
  23:          });
  24:   
  25:          $('#btn1').click(function() {
  26:              alert($('#productname').val());
  27:          })
  28:      });


从上面的代码中,看出我们可以配制它的参数,max为最大返回数,minChar为最小匹配字符,delay为延迟时间,还有formatItem,formatMatch的callback,更多参数可以参考官方document.

好了,到这里,完了,可以看下效果:

autocomplete_shot1

希望这篇Post对您有帮助。

Author:Petter Liu     http://wintersun.cnblogs.com

你可能感兴趣的:(autocomplete)