ASP.NET Returning JSON with ASHX

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

context.Response.Write(
    jsonSerializer.Serialize(
        new
        {
            query = "Li",
            suggestions = new[] { "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania" },
            data = new[] { "LR", "LY", "LI", "LT" }
        }
    )
);

Method 2

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/

Method 3

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;} 
}

Method 4

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'}, ...]
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x