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.
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.
context.Response.Write( jsonSerializer.Serialize( new { query = "Li", suggestions = new[] { "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania" }, data = new[] { "LR", "LY", "LI", "LT" } } ) );
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With