ASP. NET MVC uses Jquery.ajax

Source: Internet
Author: User

Use to: Jquery.js and Newtonsoft.Json.dll

Client Invocation Method:

$ ("#ButAjax"). Click (function () {
$.ajax ({
Type: "POST",//default is get
URL: "/ajaxtest/getperson",
Data: "Id=1&firstname=c&lastname=hy",
Async:true,//Async
Cache:false,//Do not load cache
Success:function (obj) {
Alert (obj.id + obj. FirstName + obj. LastName + obj. Man);
},
Error:function () {
Alert ("Request Failed");
}
});
});

$ ("#ButAjax2"). Click (function () {
$.ajax ({
Type: "POST",//default is get
URL: "/ajaxtest/getperson2?id=3&firstname=c&lastname=hy",
Async:true,//Async
Cache:false,//Do not load cache
Success:function (obj) {
Alert (obj.id + obj. FirstName + obj. LastName + obj. Man);
},
Error:function () {
Alert ("Request Failed");
}
});
});

$ ("#ButAjax3"). Click (function () {
$.ajax ({
Type: "POST",//default is get
URL: "/ajaxtest/getstring",
Async:true,//Async
Cache:false,//Do not load cache
Success:function (str) {
alert (str);
},
Error:function () {
Alert ("Request Failed");
}
});
});

$ ("#ButAjax4"). Click (function () {
$.ajax ({
Type: "POST",//default is get
URL: "/ajaxtest/getjsonstring",
Async:true,//Async
Cache:false,//Do not load cache
Success:function (str) {
var obj = eval (str);
$.each (obj, function (item, value) {
Alert (item + ":" + Obj[item]);
});
},
Error:function () {
Alert ("Request Failed");
}
});
});

//================================================================

$ ("#ButJson1"). Click (function () {
$.getjson ("/ajaxtest/getjson1", {ID: "$", FirstName: "C1", LastName: "HY1"}, function (JSON) {
alert (JSON);
$.each (JSON, function (item, value) {
Alert (item + ":" + Json[item]);
});
});
});

$ ("#ButJson2"). Click (function () {
$.getjson ("/ajaxtest/getjson2", {ID: "$", FirstName: "C1", LastName: "HY1"}, function (JSON) {
alert (JSON);
$.each (JSON, function (item, value) {
Alert (item + ":" + Json[item]);
});
});
});

$ ("#ButJson3"). Click (function () {
$.getjson ("/ajaxtest/getjson3", {ID: "$", FirstName: "C1", LastName: "HY1"}, function (JSON) {
alert (JSON);
$.each (JSON, function (item, value) {
Alert (item + ":" + Json[item]);
});
});
});

$ ("#ButJson4"). Click (function () {
$.getjson ("/ajaxtest/getjsonserializingjson", {ID: "$", FirstName: "C1", LastName: "HY1"}, function (JSON) {
alert (JSON);
$.each (JSON, function (item, value) {
Alert (item + ":" + Json[item]);
});
});
});

$ ("#ButJson5"). Click (function () {
$.getjson ("/ajaxtest/getjsondeserializingjson", {json: ' {"ID": 201, "FirstName": "C", "LastName": "HY", "Man": True} '}, function (JSON) {
alert (JSON);
$.each (JSON, function (item, value) {
Alert (item + ":" + Json[item]);
});
});
});

//================================================================

$ ("#ButSerializing"). Click (function () {
$.ajax ({
Type: "POST",
URL: "/ajaxtest/testserializingjson",
Data: "Id=101&firstname=c&lastname=hy&man=false",
Async:true,
Cache:false,
Success:function (obj) {
alert (obj);
},
Error:function () {
Alert ("Request Failed");
}
});
});

$ ("#ButDeSerializing"). Click (function () {
$.ajax ({
Type: "POST",
URL: "/ajaxtest/testdeserializingjson",
Data: ' json={' ID: 201, "FirstName": "C", "LastName": "HY", "Man": true} ',
Async:true,
Cache:false,
Success:function (obj) {
Alert (obj.id + obj. FirstName + obj. LastName + obj. Man);
},
Error:function () {
Alert ("Request Failed");
}
});
});

$ ("#ButSerializingList"). Click (function () {
$.ajax ({
Type: "POST",
URL: "/ajaxtest/serializinglist",
Data: "",
Async:true,
Cache:false,
Success:function (obj) {
Alert (obj + "Length:" + obj.length);
$.each (obj, function () {
$.each (This, function (item, value) {
Alert (item + ":" + Json[item]);
});
});
},
Error:function () {
Alert ("Request Failed");
}
});
});

Controllers Code:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Runtime.Serialization.Json;
Using System.Web;
Using SYSTEM.WEB.MVC;

Namespace Mvcapplication.controllers
{
public class Person
{
public int ID {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public bool Mans {get; set;}
}

public class Ajaxtestcontroller:controller
{
#region ===============$. Ajax Test =================
<summary>
Test return Object
</summary>
<param name= "Form" ></param>
<returns></returns>
Public Jsonresult Getperson (formcollection form)
{
Person p = new person
{
ID = Int. Parse (form["ID"]),
FirstName = form["FirstName"],
LastName = form["LastName"]
};
Return Json (P);
}

<summary>
tested Discovery: When you define {Controller}/{action}/{id} in global
The ID value is "" When the foreground Url?id=3&firstname=c&lastname=hy is uploaded to the background
So define global as {Controller}/{action}/{uid}
</summary>
<param name= "ID" ></param>
<param name= "FirstName" ></param>
<param name= "LastName" ></param>
<returns></returns>
Public Jsonresult GetPerson2 (string ID, String FirstName, String LastName)
{
Person p = new person
{
ID = Int. Parse (ID),
FirstName = FirstName,
LastName = LastName
};
Return Json (P);
}

<summary>
Test return string
</summary>
<returns></returns>
Public Contentresult getString ()
{
Return Content ("{ID: ' 2 ', FirstName: ' C ', LastName: ' HY '}");
}

<summary>
Test returns a JSON string
</summary>
<returns></returns>
Public Contentresult getjsonstring ()
{
Return Content ({id: ' 2 ', FirstName: ' C ', LastName: ' HY '});
}

#endregion

#region ==============$.getjson (return to JSON format test) ============

<summary>
Test finds must be double quotation marks (") cannot be single quotation marks (')
</summary>
<param name= "Code" ></param>
<param name= "FirstName" ></param>
<param name= "LastName" ></param>
<returns></returns>
Public Contentresult GetJson1 (string ID, String FirstName, String LastName)
{
Return Content ("{\" id\ ": 1,\" name\ ": \" chy\ ", \" flag\ ": true}");
}

<summary>
Test finds must be double quotation marks (") cannot be single quotation marks (')
</summary>
<param name= "Code" ></param>
<param name= "FirstName" ></param>
<param name= "LastName" ></param>
<returns></returns>
Public Contentresult GetJson2 (string ID, String FirstName, String LastName)
{
Return Content ("{\" id\ ": \" 2\ ", \" name\ ": \" chy\ "}");
}

<summary>
test finds must be double quotation marks (") cannot be single quotation marks (')
Wrong front desk Not responding
</summary>
<param name= "Code" ></param>
<param name= "FirstName" ></param>
<param name= "LastName" ></param>
<returns></returns>
Public Contentresult GetJson3 (string ID, String FirstName, String LastName)
{
Return Content ("{' id ': ' 3 '}");
}

#endregion

#region ============newtonsoft.json.dll (Json serialization and deserialization test) =============

<summary>
/// $. Ajax serialization JSON
</summary>
<param name= "ID" ></param>
<param name= "FirstName" ></param>
<param name= "LastName" ></param>
<returns></returns>
Public Contentresult Testserializingjson (formcollection form)
{
Person p = new person
{
ID = Int. Parse (form["ID"]),
FirstName = form["FirstName"],
LastName = form["LastName"]
};
Return Content (Newtonsoft.Json.JsonConvert.SerializeObject (p));
}

<summary>
/// $. Ajax deserialization JSON
</summary>
<param name= "Form" ></param>
<returns></returns>
Public Jsonresult Testdeserializingjson (formcollection form)
{
Person p = newtonsoft.json.jsonconvert.deserializeobject<person> (form["Json"). ToString ());
Return Json (P);
}

<summary>
$.getjson Serialization JSON
</summary>
<param name= "ID" ></param>
<param name= "FirstName" ></param>
<param name= "LastName" ></param>
<returns></returns>
Public Contentresult Getjsonserializingjson (string ID, String FirstName, String LastName)
{
Person p = new person
{
ID = Int. Parse (ID),
FirstName = FirstName,
LastName = LastName
};
Return Content (Newtonsoft.Json.JsonConvert.SerializeObject (p));
}

<summary>
$.getjson deserialization JSON
</summary>
<param name= "Form" ></param>
<returns></returns>
Public Contentresult Getjsondeserializingjson (string json)
{
Person p = newtonsoft.json.jsonconvert.deserializeobject<person> (Json);
Return Content (Newtonsoft.Json.JsonConvert.SerializeObject (p));
}

#endregion

#region ================ returns the collection ================

Public Jsonresult serializinglist ()
{
list<person> ls = new list<person> ();
Ls. ADD (New person
{
ID = 1,
FirstName = "C",
LastName = "HY",
Man = False
});

Ls. ADD (New person
{
ID = 2,
FirstName = "Z",
LastName = "JJ",
Man = True
});
return Json (LS);
}

Public Jsonresult deserializinglist (string json)
{
list<person> LISTP = new list<person> ();

List<string> liststr = json. Split (', '). Tolist<string> ();

foreach (string s in Liststr)
{
Listp.add (newtonsoft.json.jsonconvert.deserializeobject<person> (s));
}

Return Json (LISTP);
}

#endregion
}
}

Reproduced in original: http://blog.163.com/china__xuhua/blog/static/1997231692011101842121717/

ASP. NET MVC uses Jquery.ajax

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.