在jQuery建议中正确格式化JSON数据

时间:2014-01-02 06:57:49

标签: c# jquery asp.net json

按照示例here,我已经能够创建一个Web服务来将JSON返回到我的jQuery autosuggest文本框。

我可以获取数据,但在下拉区域中似乎采用怪异格式显示为[“示例1”,“示例2”)并垂直堆叠,而不是按照应有的方式水平堆叠每个名称。我使用JSON在Web服务中序列化我的数据并返回json而不是串。这可能与它有关,或者它可能是我的javascript中返回的格式类型?

以下是我的网络表单上的脚本..

<script type="text/javascript">
     $(document).ready(function () {
         $("#<%=ClientSearch.ClientID %>").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '<%=ResolveUrl("~/GetClients.asmx/GetClientNames") %>',
                data: "{ 'prefix': '" + request.term + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data.d, function (item) {
                        return {
                            label: item.split('-')[0],
                            val: item.split('-')[1]
                        }
                    }))
                },
                error: function (response) {
                    alert(response.responseText);
                },
                failure: function (response) {
                    alert(response.responseText);
                }
            });
        },
        select: function (e, i) {
            $("#<%=hfClientID.ClientID %>").val(i.item.val);
        },
        minLength: 1
    });
 });
</script>

最后,这是网络服务..

JavaScriptSerializer js = new JavaScriptSerializer();
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetClientNames(string prefix)
{
    List<string> clients = new List<string>();
    using (SqlCeConnection conn = new SqlCeConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlCeCommand cmd = new SqlCeCommand())
        {
            cmd.CommandText = "SELECT [Name], [ID] FROM [Current] WHERE " + "[Name] LIKE " + "'" + prefix + "%'";
            cmd.Connection = conn;
            conn.Open();
            SqlCeDataReader sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                clients.Add(string.Format("{0}-{1}", sdr["Name"], sdr["ID"]));
            }

            conn.Close();
        }
        string json = js.Serialize(clients);
        return json;
    }
}

我已经通过了jquery网站上的自动完成文档,但我似乎无法将数据格式化为我需要它。 有什么建议吗?

3 个答案:

答案 0 :(得分:4)

为什么要手动JSON序列化?你不应该。摆脱这个JavaScriptSerializer和:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<string> GetClientNames(string prefix)
{
    List<string> clients = new List<string>();
    using (SqlCeConnection conn = new SqlCeConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlCeCommand cmd = new SqlCeCommand())
        {
            cmd.CommandText = "SELECT [Name], [ID] FROM [Current] WHERE " + "[Name] LIKE " + "'" + prefix + "%'";
            cmd.Connection = conn;
            conn.Open();
            SqlCeDataReader sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                clients.Add(string.Format("{0}-{1}", sdr["Name"], sdr["ID"]));
            }

            conn.Close();
        }
        return clients;
    }
}

答案 1 :(得分:1)

我们试试这个:

while(sdr.Read) 
{
    clients = clients.Add(string.Format("[{0}-{1}]", sdr["Name"], sdr["ID"]);
}

答案 2 :(得分:0)

您无需进行拆分。使用连字符是不安全的,因为您的数据可能包含它们。

[WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public List<ItemModel> GetVendors(string prefix)
        {
            var vendors = new List<ItemModel>();
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "SELECT NAME, VEND_ID FROM VENDORS WHERE NAME LIKE @SearchText + '%'" + " ORDER BY NAME";
                    cmd.Parameters.AddWithValue("@SearchText", prefix.ToUpper().Trim());
                    cmd.Connection = conn;
                    conn.Open();

                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            var item = new ItemModel()
                            {
                                Name = sdr["NAME"].ToString(),
                                ID = (int)sdr["VEND_ID"]
                            };
                            vendors.Add(item);
                        }
                    }
                    conn.Close();
                }
                return vendors;
            }
        }

然后在你的剧本中:

success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.Name,
                                val: item.ID
                            }
                        }))
                    },