When calling jquery's Ajax method, jquery serializes the parameter data according to the Post or get protocol;
If the submitted data uses complex JSON data, for example:
{userid:32323,username:{firstname: "Lee", lastName: "Li Mouth"}}
Then the server is unable to receive the complete parameter normally, because jquery to the data serialization, is uses the key value to assemble the way;
The parameters are assembled into userid=32323&username=object; The object that the username points to is serialized as a string "object"
How can I submit a complex object to a background action parameter?
First, solve the problem of jquery for parameter serialization:
Copy Code code as follows:
/* Object serialized As String * *
String.toserialize = function (obj) {
var ransfercharforjavascript = function (s) {
var newstr = S.replace (
/[\x26\x27\x3c\x3e\x0d\x0a\x22\x2c\x5c\x00]/g,
function (c) {
ASCII = c.charcodeat (0)
Return ' \\u00 ' + (ASCII < 16?) ' 0 ' + ascii.tostring: ascii.tostring (16))
}
);
return newstr;
}
if (obj = = null) {
return null
}
else if (Obj.constructor = = Array) {
var builder = [];
Builder.push ("[");
For (var index in obj) {
if (typeof obj[index] = = "function") continue;
if (Index > 0) builder.push (",");
Builder.push (String.toserialize (Obj[index));
}
Builder.push ("]");
Return Builder.join ("");
}
else if (Obj.constructor = = Object) {
var builder = [];
Builder.push ("{");
var index = 0;
for (var key in obj) {
if (typeof obj[key] = = "function") continue;
if (Index > 0) builder.push (",");
Builder.push (String.Format ("\" {0}\ ": {1}", Key, String.toserialize (Obj[key)));
index++;
}
Builder.push ("}");
Return Builder.join ("");
}
else if (Obj.constructor = = Boolean) {
return obj.tostring ();
}
else if (Obj.constructor = = number) {
return obj.tostring ();
}
else if (Obj.constructor = = String) {
Return String.Format (' {0} ', Ransfercharforjavascript (obj));
}
else if (Obj.constructor = = Date) {
Return String.Format (' {__datatype ': ' Date ', ' __thisue ': {0}} ', Obj.gettime ()-(New Date (1970, 0, 1, 0, 0, 0)). GetTime ());
}
else if (this.tostring!= undefined) {
return string.toserialize (obj);
}
}
jquery Asynchronous Request:
Copy Code code as follows:
$ (function () {
/* Button click event * *
$ ("#btn_post_test"). Click (function () {
var data = [
{UserId: "One", UserName: {FirstName: "323", LastName: "2323"}, Keys: ["Xiaoming", "Xiaohong"]},
{UserId: "UserName": {FirstName: "323", LastName: "2323"}, Keys: ["Xiaoming", "Xiaohong"]},
{UserId: "UserName": {FirstName: "323", LastName: "2323"}, Keys: ["Xiaoming", "Xiaohong"]}
];
$.post ("Home/test", {users:String.toSerialize (data)}, function (text) {
Alert (string.toserialize (text));
}, "JSON");
});
});
Click the button to submit the data, monitor the browser, and you can find that the submitted data is serialized by the JSON object:
Copy Code code as follows:
Post/home/test http/1.1
X-requested-with:xmlhttprequest
Accept-language:zh-cn
Referer:http://localhost:3149/test.html
Accept:application/json, Text/javascript, */*
content-type:application/x-www-form-urlencoded
Accept-encoding:gzip, deflate
user-agent:mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; trident/4.0; SLCC2. NET CLR 2.0.50727;. NET CLR 3.5.30729;. NET CLR 3.0.30729; Media Center PC 6.0; infopath.2;. net4.0c;. NET4.0E)
host:localhost:3149
content-length:501
Connection:keep-alive
Cache-control:no-cache
cookie:cookiegloballoginuserid=16063
users=%5b%7b%22userid%22%3a%2211%22%2c%22name%22%3a%7b%22firstname%22%3a%22323%22%2c%22lastname%22%3a%222323% 22%7d%2c%22keys%22%3a%5b%22xiaoming%22%2c%22xiaohong%22%5d%7d%2c%7b%22userid%22%3a%2222%22%2c%22name%22%3a%7b% 22firstname%22%3a%22323%22%2c%22lastname%22%3a%222323%22%7d%2c%22keys%22%3a%5b%22xiaoming%22%2c%22xiaohong%22% 5d%7d%2c%7b%22userid%22%3a%2233%22%2c%22name%22%3a%7b%22firstname%22%3a%22323%22%2c%22lastname%22%3a%222323%22 %7d%2c%22keys%22%3a%5b%22xiaoming%22%2c%22xiaohong%22%5d%7d%5d
Second, the background server handles parameter bindings:
Copy Code code as follows:
Using System.Collections.Generic;
Using SYSTEM.WEB.MVC;
Using Newtonsoft.json;
Using Newtonsoft.Json.Linq;
Namespace Webos.controllers
{
[HandleError]
public class Homecontroller:controller
{
<summary>
Test method
</summary>
<param name= "Users" > User Data </param>
<returns> submitted user Array </returns>
Public ActionResult Test ([Modelbinder (typeof (Jsonbinder<user>))]list<user> users)
{
Return Json (Users, Jsonrequestbehavior.allowget);
}
}
<summary>
Object entity
</summary>
[Jsonobject]
public class User
{
[Jsonproperty ("UserName")]
Public UserName Name {get; set;}
[Jsonproperty ("UserId")]
public string UserId {get; set;}
[Jsonproperty ("Keys")]
Public list<string> Keys {get; set;}
}
<summary>
Object entity
</summary>
[Jsonobject]
public class UserName
{
[Jsonproperty ("FirstName")]
public string FirstName {get; set;}
[Jsonproperty ("LastName")]
public string LastName {get; set;}
}
<summary>
JSON data binding class
</summary>
<typeparam name= "T" ></typeparam>
public class Jsonbinder<t>: Imodelbinder
{
public Object Bindmodel (ControllerContext controllercontext, Modelbindingcontext BindingContext)
{
Get the submitted parameter data from the request
var json = Controllercontext.httpcontext.request.form[bindingcontext.modelname] As String;
The Submit parameter is an object
if (JSON. StartsWith ("{") && json. EndsWith ("}"))
{
Jobject jsonbody = Jobject.parse (JSON);
Jsonserializer js = new Jsonserializer ();
Object obj = js. Deserialize (Jsonbody.createreader (), typeof (T));
return obj;
}
The commit parameter is an array
if (JSON. StartsWith ("[") && json. EndsWith ("]"))
{
ilist<t> list = new list<t> ();
Jarray JSONRSP = Jarray.parse (JSON);
if (JSONRSP!= null)
{
for (int i = 0; i < Jsonrsp.count; i++)
{
Jsonserializer js = new Jsonserializer ();
Object obj = js. Deserialize (Jsonrsp[i]. Createreader (), typeof (T));
List. ADD ((T) obj);
}
}
return list;
}
return null;
}
}
}
The front-end gets the data returned in the background, and the result is the data submitted by the User:
Background Json deserialization uses the Newtonsoft.json component, for information refer to: http://james.newtonking.com/