简体   繁体   English

将ASP.NET Web服务结果传递给jQuery AutoSuggest插件

[英]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. 我有一个ASP.NET Web服务,该服务以JSON格式返回用户的朋友列表,以便它可以填充AutoSuggest插件数据源。 I'm using ASP.NET 4.0 and jQuery 1.4.4 minified. 我正在使用ASP.NET 4.0和jQuery 1.4.4缩小版。 When I try to invoke the autoSuggest method, the following code doesn't seem to work. 当我尝试调用autoSuggest方法时,以下代码似乎不起作用。 It applies the startText value to my text box, but it doesn't populate the datasource. 它将startText值应用于我的文本框,但不填充数据源。

$(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: 这是我的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);
}

Any suggestions on how I should populate the data source for the AutoSuggest plugin from my web service? 关于如何从Web服务填充AutoSuggest插件的数据源的任何建议? Here's a link to the developer's page: http://code.drewwilson.com/entry/autosuggest-jquery-plugin 这是开发人员页面的链接: 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. 经过更多研究后,我发现ASP .NET WebServices不会先返回XML才返回数据。 I decided to go with a generic handler and render the JSON using the handler. 我决定使用通用处理程序,并使用该处理程序呈现JSON。 I used my existing code to encode the JSON and then rendered the JSON like this: 我使用现有代码对JSON进行编码,然后以如下方式呈现JSON:

    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. 我将上面的代码放入处理程序的ProcessRequest方法中,现在一切正常。 There may be other methods to render JSON available, but this one works for the time being. 可能还有其他方法可以使JSON可用,但是这种方法暂时可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM