开发者

JQuery AutoComplete Source Issue C#

I am trying to get a simple example of how to us the AutoComplete JQuery plug-in work but running into some issue. The code is written in C# (2008) without using MVC.

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">    
        <title></title>
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" /> 
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>  
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>   
        <script type="text/javascript">

            $(document).ready(function() {
                //GetFormulary();
                LoadAutoComplete();
            });

            function LoadAutoComplete() {
                $("#quickSearchTextBox").autocomplete({
                    source: function(request, response) {
                        $.ajax({
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            url: "/WebSite1/Default.aspx/GetTest2",
                            data: "{}",
                            dataType: "json",
                            success: function(data) {
                                response($.map(data, function(item) {
                                    return {
                                        label: item.TestName,
                                        value: item.TestName
                                    }
                                }));
                            }
                        });
                    },
                    minLength: 2
                });
            }                     
        </script>

    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        <table id="quickSearchTable" border="0">
        <tbody>
            <tr>
                <td>
                    <input style="width: 100%" id="quickSearchTextBox" title="Enter search words" maxlength="200" value="" />
                </td>            
            </tr>
        </tbody>
    </table>
    <div id="searchResults" style="display: none;">
    </div>
        </div>
        </form>
    </body>
    </html>

Code Behind:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    using Syst开发者_C百科em.Web.UI;

    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }


        [WebMethod]
        public static string GetTest1()
        {
            return GetFTest2("art");
        }

        private static string GetFTest2(string searchPhrase)
        {
            var formularyTests = new List<FormularyTest>();

            const string connectionString = "";

            using (var sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();
                var sqlCommand = new SqlCommand("Search", sqlConnection) { CommandType = CommandType.StoredProcedure };
                sqlCommand.Parameters.Add(new SqlParameter("@Phrase", searchPhrase));
                SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
                while (sqlDataReader.Read())
                {
                    formularyTests.Add(new FormularyTest { Name = sqlDataReader["LongName"].ToString() });
                }
            }
            var jSearializer = new JavaScriptSerializer();
            return jSearializer.Serialize(formularyTests);        
        }

        [WebMethod]
        public static List<FormularyTest> GetTest2()
        {
            return GetFTest1("arterial");
        }

        private static List<FormularyTest> GetFTest1(string searchPhrase)
        {
            var formularyTests = new List<FormularyTest>();

            const string connectionString = "";

            using (var sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();
                var sqlCommand = new SqlCommand("Search", sqlConnection) { CommandType = CommandType.StoredProcedure };
                sqlCommand.Parameters.Add(new SqlParameter("@Phrase", searchPhrase));
                SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
                while (sqlDataReader.Read())
                {
                    formularyTests.Add(new FormularyTest { Name = sqlDataReader["LongName"].ToString() });
                }
            }

            return formularyTests;
        }
    }

    public class FormularyTest
    {
        public string Name { get; set; }
        public string Url { get; set; }
    }

JQuery AutoComplete Source Issue C#

For some reason I cannot get anything to show up in the textbox. A little help would be much appreciated.


The JavaScriptSerializer is returning a result in the format of:

{d:"[{\"Name\":\"Test 1\",\"Url\":\"url1\"},{\"Name\":\"Test 2\",\"Url\":\"url2\"}]"}

So, data.d would give you your serialized string [{"Name":"Test 1","Url":"url1"},{"Name":"Test 2","Url":"url2"}]. That woudl be closer to what you want, but you're really after a JSON array version of that string. If you use eval(data.d) instead of data in your success function, it will work. Admittedly, using eval is an imperfect solution, but it does allow your code to "work".

The following JavaScript has the change:

        function LoadAutoComplete() {
            $("#quickSearchTextBox").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "/Service.asmx/Test",
                        data: "{'searchTerm':'" + request.term + "'}",
                        dataType: "json",
                        async: true,
                        success: function (data) {
                            response($.map(eval(data.d), function (item) {
                                return {
                                    label: item.Name,
                                    value: item.Url
                                }
                            }));
                        },
                        error: function (result) {
                            alert("Error loading the data");
                        }
                    });
                },
                minLength: 2
            });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜