Pass ASP.NET Web Service Result to jQuery AutoSuggest Plugin
I have an ASP.NET web service that returns a user's friends list in JSON form so that it may populate the AutoSuggest plugin data source. I'm using ASP.NET 4.0 and jQuery 1.4.4 minified. When I try to invoke the autoSuggest method, the following code doesn't seem to work. It applies the startText value to my text box, but it doesn't populate the datasource.
$(document).ready(function () {
$("input[type=text]").autoSuggest("GetFriends.asmx/GetFriendsList", { minChars: 2, matchCase: false, startText: "Search Username" });
});
Here's my text box control:
<asp:TextBox ID="tbSearch" runat="server"></asp:TextBox>
Here's the relevant part to my web service:
[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();
friend开发者_运维问答s.Add(friend);
}
return JsonConvert.SerializeObject(friends, Formatting.Indented);
}
Any suggestions on how I should populate the data source for the AutoSuggest plugin from my web service? Here's a link to the developer's page: http://code.drewwilson.com/entry/autosuggest-jquery-plugin
After doing a little more research, I found that ASP .NET WebServices do not return data without being enclosed in XML first. I decided to go with a generic handler and render the JSON using the handler. I used my existing code to encode the JSON and then rendered the JSON like this:
string str = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);
context.Response.ContentType = "application/json";
context.Response.Write(str);
I put the above code in the ProcessRequest method of my handler and all works well now. There may be other methods to render JSON available, but this one works for the time being.
精彩评论