2、新建返回json对象的类“ResponseData.cs”
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Collections.Generic; namespace WebLogin { public class ResponseData { private bool success; public bool Success { get { return success; } set { success = value; } } private string message; public string Message { get { return message; } set { message = value; } } private List<Msg> msgs; public List<Msg> Msgs { get { return msgs; } set { msgs = value; } } public ResponseData(bool success, string message) { this.success = success; this.message = message; } public ResponseData(bool success, string message, List<Msg> msgs) { this.success = success; this.message = message; this.msgs = msgs; } } }3、去官网下载Json.NET,并复制引用
官网:
下载地址:
下载解压后将“Newtonsoft.Json.dll”复制到项目的“bin”目录中,并引用(注意和.net版本保持一致)
4、新建一般处理程序“reg.ashx”
using System; using System.Collections; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; using System.Collections.Generic; using Newtonsoft.Json;//引入 namespace WebLogin { /// <summary> /// $codebehindclassname$ 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class reg : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json";//设置响应内容的格式是json格式 string id = context.Request["id"]; string pwd = context.Request["pwd"]; string name = context.Request["name"]; List<Msg> msgs = new List<Msg>(); if (String.IsNullOrEmpty(id)) { msgs.Add(new Msg("idMsg", "用户名不能为空.")); } if (String.IsNullOrEmpty(pwd)) { msgs.Add(new Msg("pwdMsg", "密码不能为空.")); } if (String.IsNullOrEmpty(name)) { msgs.Add(new Msg("nameMsg", "姓名不能为空.")); } ResponseData rData; if (msgs.Count == 0) { //调用注册方法,写入数据库 rData = new ResponseData(true, "注册成功."); } else { rData = new ResponseData(false, "注册失败.", msgs); } context.Response.Write(JsonConvert.SerializeObject(rData));//直接调用方法将rData转换为json字符串 } public bool IsReusable { get { return false; } } } }四、完成效果如图
以上所述是小编给大家介绍的ASP.NET使用Ajax返回Json对象的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!