ASP. NET uses Ajax to return a Json object, ajaxjson

Source: Internet
Author: User

ASP. NET uses Ajax to return a Json object, ajaxjson

1. Create an html page, such as the registration page "Register.htm"

<! DOCTYPE html> 

2. Create a js file, such as reg. js.

$ (Function () {// function clearMsg () {$ (". msg ").html (" ");} // defines the function for getting form data. Note that the json object function formData () {return {id: $ (" # id ") is returned "). val (), pwd: $ ("# pwd "). val (), name: $ ("# xm "). val () };}// define the function reg () {var url = "Register. ashx "; var data = formData (); clearMsg (); $. ajax ({type: 'get', // The json object is automatically converted into a query string and appended to the url, as shown in: http://localhost:49521/Register.ashx?id=a&pwd=b&name=c Url: url, dataType: 'json', // The server must return a json data type, for example, {"success": true, "message ": "registered"} contentType: 'application/json', // The type of content encoding data: data when the message is sent to the server, // the data submitted to the server, directly use the data of the json object, such as: {"id": "a", "pwd": "B", "name ": "c"} (if a string in json format is required, JSON can be used. stringify (data) success: function (responseData) {// if the response is successful (that is, 200) if (responseData. success = true) {// responseData is also in json format, for example, {"success": true, "message": "registered successfully"} alert (re Eclipsedata. message);} else {var msgs = responseData. msgs; // The msgs object is an array, as shown below: // {"success": false, "message": "registration failed", "msgs ": [{"id": "pwdMsg", "message": "The password cannot be blank. "},{" id ":" nameMsg "," message ":" The name cannot be blank. "}]} for (var I = 0; I <msgs. length; I ++) {$ ('#' + msgs+ I }.id+.html (msgs [I]. message) ;}}, error: function () {// required parameter of the Function type, the function called when the request fails. This function has three parameters: XMLHttpRequest object, error message, and captured error object (optional ). Ajax event functions are as follows: // function (XMLHttpRequest, textStatus, errorThrown) {// generally, textStatus and errorThrown have only one of them containing information. // this; // The options parameter alert (arguments [1]) ;}} passed when calling this ajax request; // ajax} // defines an initialization function init () {$ ("# btnReg "). click (function () {reg () ;}) ;}// call the initialization function init ();});

3. Process ajax requests

Method 1: manually splice json strings

Create a general processing program, such as Register. 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; namespace WebLogin {// <summary> /// $ codebehindclassname $ abstract description /// </summary> [WebService (Namespace =" http://tempuri.org/ ")] [WebServiceBinding (ConformsTo = WsiProfiles. basicProfile1_1)] public class Register1: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = "application/json"; // set the response content format to json string id = context. request ["id"]; string pwd = context. request ["pwd"]; string name = context. request ["name"]; List <string> msgList = new List <string> (); if (String. isNullOrEmpty (id) {msgList. add ("{\" id \ ": \" idMsg \ ", \" message \ ": \" username cannot be blank. \ "}");} if (pwd = null | pwd = "") {msgList. add ("{\" id \ ": \" pwdMsg \ ", \" message \ ": \" the password cannot be blank. \ "}"); // format: {"id": "pwdMsg", "message": "The password cannot be blank. "}} if (name = null | name =" ") {msgList. add ("{\" id \ ": \" nameMsg \ ", \" message \ ": \" name cannot be blank. \ "}");} string responseText = ""; if (msgList. count = 0) {// call the background code to write data to the database responseText = "{\" success \ ": true, \" message \": \ "registration successful \"} ";}else {string msgsValue =" "; for (int I = 0; I <msgList. count; I ++) {msgsValue + = msgList [I] + ","; // connect each string in the list, separated, but there will be more ","} msgsValue = msgsValue. substring (0, msgsValue. length-1); // remove the "," msgsValue = "[" + msgsValue + "]"; // use "[]", for example: [{"id": "pwdMsg", "message": "The password cannot be blank. "},{" id ":" nameMsg "," message ":" The name cannot be blank. "}] responseText =" {\ "success \": false, \ "message \": \ "registration failed \", \ "msgs \": "+ msgsValue +"} "; // The most effective format is {" success ": false," message ":" failed to register "," msgs ": [{"id": "pwdMsg", "message": "The password cannot be blank. "},{" id ":" nameMsg "," message ":" The name cannot be blank. "}]} context. response. write (responseText);} public bool IsReusable {get {return false ;}}}}

Method 2: Use the Json. NET tool to convert the C # object to json output.

1. Create an Information Class "Msg. 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;namespace WebLogin{  public class Msg  {    private string id;    public string Id    {      get { return id; }      set { id = value; }    }    private string message;    public string Message    {      get { return message; }      set { message = value; }    }    public Msg(string id, string message)    {      this.id = id;      this.message = message;    }  }}

2. Create a class "ResponseData. cs" that returns a json object"

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. Download Json. NET from the official website and copy the reference.

Official Website: http://www.newtonsoft.com/json

: Http://pan.baidu.com/s/1nvz9JBV

Download and decompress the package, copy "Newtonsoft. Json. dll" to the "bin" directory of the project, and reference it (note that it is consistent with the. net version)

4. Create the General handler "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; // introduce namespace WebLogin {// <summary> /// $ codebehindclassname $ abstract description /// </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"; // set the response content format to 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", "the user name cannot be blank. ");} if (String. isNullOrEmpty (pwd) {msgs. add (new Msg ("pwdMsg", "the password cannot be blank. ");} if (String. isNullOrEmpty (name) {msgs. add (new Msg ("nameMsg", "name cannot be blank. ");} ResponseData rData; if (msgs. count = 0) {// call the registration method and write data to the database rData = new ResponseData (true, "registration successful. ");} else {rData = new ResponseData (false," registration failed. ", msgs);} context. response. write (JsonConvert. serializeObject (rData); // directly call the method to convert rData to a json string} public bool IsReusable {get {return false ;}}}}

Iv. Completion Effect

The above is a small series of ASP. NET returns a Json object using Ajax. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.