[英]ASP.NET Returning JSON with ASHX
我正在為我的網站創建自動完成功能。 到目前為止,javascript部分已經結束了。 此外,我可以獲得匹配的用戶的MembershipUser對象。
我需要以下列格式返回JSON:
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}
這是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);
}
}
}
如何以所需格式返回json? 謝謝。
context.Response.Write(
jsonSerializer.Serialize(
new
{
query = "Li",
suggestions = new[] { "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania" },
data = new[] { "LR", "LY", "LI", "LT" }
}
)
);
這有助於我:
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將在這里找到: http : //json.codeplex.com/releases/
根據所需的返回創建一個具有契約的類,然后在該類的實例上使用JSONSerializer來創建返回內容
[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;}
}
你的json有點尷尬,因為你必須維護這兩個數組的索引。 我可以建議更像這樣的東西嗎?
{
query: 'Li',
data: [{id:'LR', text:'Liberia'}, {id:'LY', text:'Libyan Arab Jamahiriya'}, ...]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.