2010-12-19 55 views
0

我有一個ASP.NET Web服務,以JSON形式返回用戶的朋友列表,以便它可以填充AutoSuggest插件數據源。我正在使用ASP.NET 4.0和jQuery 1.4.4進行縮小。當我嘗試調用autoSuggest方法時,以下代碼似乎不起作用。它將startText值應用於我的文本框,但不會填充數據源。將ASP.NET Web服務結果傳遞給jQuery AutoSuggest插件

$(document).ready(function() { 
     $("input[type=text]").autoSuggest("GetFriends.asmx/GetFriendsList", { minChars: 2, matchCase: false, startText: "Search Username" }); 
    }); 

這裏是我的文本框控件:

<asp:TextBox ID="tbSearch" runat="server"></asp:TextBox> 

下面是相關的部分,以我的web服務:

[WebMethod] 
public string GetFriendsList() 
{ 
    DataTable dt = GetFriends(); 
    List<Friend> friends = new List<Friend>(); 
    string[] items = new string[dt.Rows.Count]; 

    for (int i=0; i< dt.Rows.Count; i++) 
    { 
     DataRow dr = dt.Rows[i]; 
     Friend friend = new Friend(); 
     friend.value= dr["UserId"].ToString(); 
     friend.name= dr["UserName"].ToString(); 
     friends.Add(friend); 
    } 
    return JsonConvert.SerializeObject(friends, Formatting.Indented); 
} 

,我應該如何填充爲自動提示插件數據源的任何建議從我的網絡服務? 這是開發人員頁面的鏈接:http://code.drewwilson.com/entry/autosuggest-jquery-plugin

回答

0

經過多一點研究後,我發現ASP .NET WebServices不會首先將數據封裝在XML中返回數據。我決定去使用通用處理程序並使用處理程序呈現JSON。我用我的現有代碼進行編碼的JSON,然後呈現的JSON這樣的:

string str = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented); 
    context.Response.ContentType = "application/json"; 
    context.Response.Write(str); 

我把上面的代碼在我的處理程序的ProcessRequest方法,目前一切運作良好。可能還有其他方法可用來呈現JSON,但這個方法暫時適用。

+0

HttpHandler是一個很好的選擇。僅供參考,ASMX服務絕對不限於XML:http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/ – 2010-12-23 07:14:56