2013-11-26 37 views
4

我正在使用JQuery UI自動完成與我的ASP.NET-C#網站。在ASP.NET中使用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

UPDATE

我想是這樣的:

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

Web方法相當於GetAvailableTags()

[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調用不被解僱。可能是什麼原因?

+0

您可以根據自己的目的對這個示例進行復制:http://stackoverflow.com/questions/20150130/ajax-and-php-to-enter-multiple-forms-input-to-database/20150474#20150474 – MonkeyZeus

回答

5

我建議在服務器端使用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屬性是否存在。

+0

謝謝,它現在正在工作,我的意思是ajax獲取數據,但AutoComplete不起作用。數據沒有顯示在那裏。請幫忙。 –

0

我有一個很好的解決方案,我在一個Intranet應用程序中實現;它使用帶有HttpHandler的jQuery UI自動完成功能,只搜索以輸入內容開頭的客戶;它也僅在輸入3個或更多字符時觸發。這意味着你永遠不會檢索整個表格,只是它的一個子集。

首先是HttpHandler。我不會進入數據檢索的螺母和螺栓,因爲你可以自己弄清楚這個部分。可以說它調用一個存儲過程來返回名稱以(以任何方式發送到Handler)開頭的客戶,並將一個JSON序列化的匹配數組返回給Autocomplete處理程序。

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

讓我知道如果這有幫助,我可以通過電子郵件發送相關的源文件,如果你想。