小编典典

ASP.NET使用ASHX返回JSON

ajax

我正在为我的网站创建自动完成功能。到目前为止,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?谢谢。


阅读 688

收藏
2020-07-26

共1个答案

小编典典

context.Response.Write(
    jsonSerializer.Serialize(
        new
        {
            query = "Li",
            suggestions = new[] { "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania" },
            data = new[] { "LR", "LY", "LI", "LT" }
        }
    )
);
2020-07-26