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:

 suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],

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

How can I return the json in the desired format?


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

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

Newtonsoft.Json will be found here:

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

public class YourReturnObject {
  public String Query { get;set;}

  public String[] Suggestions { get;set;}  

  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 or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x