Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 774
user1027620 Avatar asked Dec 05 '11 21:12

user1027620


People also ask

How do I return a JSON response in C#?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header.


2 Answers

context.Response.Write(     jsonSerializer.Serialize(         new         {             query = "Li",             suggestions = new[] { "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania" },             data = new[] { "LR", "LY", "LI", "LT" }         }     ) ); 
like image 169
L.B Avatar answered Sep 29 '22 07:09

L.B


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/

like image 31
BigMan Avatar answered Sep 29 '22 06:09

BigMan