我正在为我的网站创建自动完成功能。
到目前为止,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" }
}
)
);
关于c# - ASP.NET使用ASHX返回JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8392413/