32

I am creating autocomplete functionality for my website. So far, the javascript part is over. Also, I can get the MembershipUser object of the user that matches.

I need to return JSON in the following format:

{
 query:'Li',
 suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
 data:['LR','LY','LI','LT']
}

and this is the code in ashx:

public void ProcessRequest (HttpContext context) {
    System.Web.Script.Serialization.JavaScriptSerializer JsonSerializer;   
    string query = context.Request.QueryString["query"];
    System.Web.Security.MembershipUserCollection Users = System.Web.Security.Membership.GetAllUsers();
    context.Response.ContentType = "application/json";
    foreach (System.Web.Security.MembershipUser User in Users)
    {
        if (User.UserName.StartsWith(query.ToLower()))
        {
            context.Response.Write(query + Environment.NewLine);
            context.Response.Write(User.Email);
        }
    }
}

How can I return the json in the desired format? Thanks.

2
  • 2
    That is not valid JSON by the way. See: json.org Commented Dec 5, 2011 at 21:55
  • ChaosPandion, the plugin requires this output... :/ Commented Dec 5, 2011 at 22:06

4 Answers 4

39
context.Response.Write(
    jsonSerializer.Serialize(
        new
        {
            query = "Li",
            suggestions = new[] { "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania" },
            data = new[] { "LR", "LY", "LI", "LT" }
        }
    )
);
Sign up to request clarification or add additional context in comments.

Comments

28

This helps me:

using System;
using System.Data;
using System.Web;
using System.Linq;
using System.Collections;
using Newtonsoft.Json;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "application/json";
    string quer = context.Request["query"];

    DataTable _t = AMC.Core.Logic.Root.Storage.ExecuteQuery("SELECT [tag_name] FROM [tags] Where [tag_name] like '%' + @ke + '%'", new System.Data.SqlClient.SqlParameter("ke", quer));

    DataRow[] list = new DataRow[_t.Rows.Count];
    _t.Rows.CopyTo(list, 0);

    var wapper = new { 
        query = quer
        , suggestions = (from row in list select row["tag_name"].ToString()).ToArray()
        //, data = new[] { "LR", "LY", "LI", "LT" } 
    };
    context.Response.Write(JsonConvert.SerializeObject(wapper));            
}

Newtonsoft.Json will be found here: http://json.codeplex.com/releases/

1 Comment

Just to add, in IE8 (only?) this will fail when its called. A dialog will popup asking if you want to open or save the file "handler.ashx". To resolve this, change the line of code to return text: context.Response.ContentType = "text/html";
6

Create a class that has a contract based on the return you want, and then use the JSONSerializer on an instance of that class to create your return content

[DataContract]
public class YourReturnObject {
  [DataMember(Name="query")]
  public String Query { get;set;}

  [DataMember(Name="suggestions")]
  public String[] Suggestions { get;set;}  

  [DataMember(Name="data")]
  public String[] OtherData{ get;set;} 
}

1 Comment

Hi, thanks for the answer. Could you please explain a bit how this is implemented in the for loop?
5

your json is a little awkward since you have to maintain an index into both of those array. might I suggest something more like this?

{
query: 'Li',
data: [{id:'LR', text:'Liberia'}, {id:'LY', text:'Libyan Arab Jamahiriya'}, ...]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.