【问题标题】:Efficient way of using JQuery UI Autocomplete with ASP.NET在 ASP.NET 中使用 JQuery UI 自动完成的有效方法
【发布时间】:2013-12-12 04:03:31
【问题描述】:

我在我的 ASP.NET-C# 网站上使用 JQuery UI 自动完成功能。

JavaScript:

$(function () {
        var availableTags = [
            <%=GetAvaliableTags() %>
        ];
        $("input.tag_list").autocomplete({
            source: availableTags
        });
    });

代码隐藏中的 C# 函数:

public string GetAvaliableTags()
{
    var tags = new[] { "ActionScript", "Scheme" };
    return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}

这工作正常。但是我怀疑如果我从数据库中获取大量标签,它会在页面加载时立即加载所有这些标签,从而使其变慢。我想到的有效方法是使用 Ajax。但我不是 Ajax 程序员,对此知之甚少。谁能告诉我如何有效地使用Ajax?如何按需拨打GetAvailableTags

更新

我试过这样:

 $(function () {
                var availableTags = [function () {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "CreateTopic.aspx/GetAvaliableTags",
                        data: "{ 'key' : '" + $("input.tag_list").val() + "'}",
                        dataType: "json",
                        async: true,
                        dataFilter: function (data) { return data; },
                        success: function (data) {if (result.hasOwnProperty("d")) {

                          $("input.tag_list").autocomplete({
                              source: result.d
                          });
                      }
                      else {
                          // No .d; so just use result
                          $("input.tag_list").autocomplete({
                              source: result
                          });
                    });
                }];
                $("input.tag_list").autocomplete({
                    source: availableTags
                });
            });

相当于GetAvailableTags()的Web方法

[System.Web.Services.WebMethod]
public static string GetAvaliableTags(string key)
{
    var tags = new[] { "ActionScript", "Scheme" };
    return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}

但是 Ajax 调用没有被触发。可能是什么原因?

【问题讨论】:

标签: c# javascript jquery asp.net ajax


【解决方案1】:

我建议在服务器端使用 ASP.NET AJAX 页面方法并让 jQuery .ajax() 函数调用它来检索数据,如下所示:

代码隐藏:

[WebMethod]
public static string GetAvailableTags()
{
    // Put logic here to return list of tags (i.e. load from database)
    var tags = new[] { "ActionScript", "Scheme" };
    return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}

标记:

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "PageName.aspx/GetAvailableTags",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            if (result.hasOwnProperty("d")) {
                // The .d is part of the result so reference it
                //  to get to the actual JSON data of interest
                $("input.tag_list").autocomplete({
                    source: result.d
                });
            }
            else {
                // No .d; so just use result
                $("input.tag_list").autocomplete({
                    source: result
                });
            }
        }
    });
});

注意:您需要将 PageName.aspx 的名称更改为 .aspx 页面的名称。此外,.d 语法是 Microsoft 在 ASP.NET AJAX 的 ASP.NET 3.5 版本中提供的反 XSS 保护;因此检查.d 属性是否存在。

【讨论】:

  • 谢谢,它现在可以工作了,我的意思是 ajax 正在获取数据,但 AutoComplete 不工作。那里没有显示数据。请帮忙。
【解决方案2】:

我在 Intranet 应用程序中实现了一个很好的解决方案;它使用带有 HttpHandler 的 jQuery UI 自动完成功能,并且只搜索从输入中的任何内容开始的客户;它也仅在输入 3 个或更多字符时触发。这意味着您永远不会检索整个表,而只是检索其中的一个子集。

首先是 HttpHandler。我不会深入探讨数据检索的具体细节,因为您可能自己可以弄清楚那部分。可以说它调用一个存储过程来返回名称以开头的客户(无论是发送到处理程序的),并将一个 JSON 序列化的匹配数组返回给自动完成处理程序。

using Newtonsoft.Json;

namespace Invoicing.HttpHandlers
{
    [WebService(Namespace = "yournamespace/http-handlers/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class CustomerHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
          // your data-retrieval logic here
          // write json to context.Response
        }
    }

如果您不习惯这种方法,我将快速描述 JSON 部分。

基本上,我有一个名为“ResponseCustomer”的小型包装类型对象,因为我只需要自动完成处理程序的客户 ID 和名称,而不是完整的客户详细信息:-

[Serializable]
public class ResponseCustomer
{
    public int ID;
    public string CustomerName;
}

IHttpHandler.ProcessRequest 调用我的存储过程,并将结果转换为 IList - 这意味着返回的 JSON 尽可能精简:-

    public void ProcessRequest(HttpContext context)
    {
        string json = string.Empty;

        // note the httpcontext.Request contains the search term
        if (!string.IsNullOrEmpty(context.Request["term"]))
        {
            string searchTerm = context.Request["term"];
            var customers = (data access component).CustomerSearch(searchTerm); // call Search stored proc

            if (customers.Count != 0)
            {
                var transformList = new List<ResponseCustomer>();

                for (int index = 0; index < customers.Count; index++)
                {
                    transformList.Add(new ResponseCustomer
                    {
                        ID = customers[index].ID,
                        CustomerName = customers[index].CustomerName
                    });
                }

                // call Newtonsoft.Json function to serialize list into JSON
                json = JsonConvert.SerializeObject(transformList);
            }

        }

        // write the JSON (or nothing) to the response
        context.Response.Write(json);
    }

到目前为止一切顺利吗?

确保此 HttpHandler 已连接到 web.config(请注意,对于 IIS6 和 IIS 7+,您必须以不同的方式执行此操作):-

      <system.web>

        <!-- Custom HTTP handlers (IIS 6.0) -->
        <httpHandlers>
          <add path="customerHandler.ashx" verb="*" type="(namespace).(handler name), (assembly name)" />

i.e.

      <add path="customerHandler.ashx" verb="*" type="MyProject.Handlers.CustomerHandler, MyProject" />

    and for IIS7: -


  <system.webServer>

    <handlers>
      <!-- Custom HTTP handlers (IIS7+) -->
      <add name="customerHandler" preCondition="integratedMode" verb="*" path="customerHandler.ashx" type="(namespace).(handler name), (assembly name)"" />

如您所知,最后连接到客户端:-

HTML:-

        <span>Customer</span>
        <span class="ui-widget" style="display:inline-block">
            <input id="txtCustomer" runat="server" clientidmode="Static" />
        </span>

JS:-

$(function ()
{
    $("#txtCustomer").autocomplete(
        {
            source: "customerHandler.ashx",
            // note minlength, triggers the Handler call only once 3 characters entered
            minLength: 3,
            select: function (event, ui)
            {
                if (ui.item)
                {
                    $("#txtCustomer").val(ui.item.CustomerName);
                    return false;
                }
            }
        })
        .data("autocomplete")._renderItem = function (ul, item)
        {
            // insert an item into the autocomplete dropdown (YMMV)
            return $("<li></li>")
                .data("item.autocomplete", item)
                .append("<a><table cellpadding='0' cellspacing='0' border='0' width='250px'><tr><td width='200' valign='top' align='left'>"
                + item.CustomerName + "</td><td width='50px' valign='top' align='left'>[ID "
                + item.ID + "]</td></tr></table></a>")
                .appendTo(ul);
        };
});

如果这有帮助,请告诉我,如果需要,我可以将相关源文件通过电子邮件发送给您。

【讨论】:

    【解决方案3】:

    如果您想实时更新选项

        $(document).ready(function() {   
                $("textbox").autocomplete({
                    source: function (request, response) {
                    pageMethod.yourmethodname(request.term,onSuccess)
                    function onSuccess(Responce){
                                      data = JSON.parse(Responce)
                                      response($.map(data.d, function (item) {
                                              return {
                                                     value: item
                                                      }
                                         }
    
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      相关资源
      最近更新 更多