Use jQuery to pass complex json data to asp.net Mvc-ModelBinder

Source: Internet
Author: User

When jQuery's ajax method is called, jQuery will serialize the parameter data based on the post or get protocol;

If the submitted data uses complex json data, for example:

{UserId: 32323, userName: {firstName: "Li", lastName: ""}}

The server cannot normally receive complete parameters because jQuery serializes data and uses key-value pairs to assemble them;

Parameters are assembled into userId = 32323 & userName = object; the object pointed to by userName is serialized into a string "object"


How can I submit a complex object to the background action parameter?

First, solve jQuery's problem of parameter serialization:
Copy codeThe Code is as follows:
/* Serialize the object to a 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 (16): 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 )). getTime ());
}
Else if (this. toString! = Undefined ){
Return String. toSerialize (obj );
}
}


JQuery asynchronous request:
Copy codeThe Code is as follows:
$ (Function (){
/* Click the event button */
$ ("# Btn_post_test"). click (function (){
Var data = [
{UserId: "11", UserName: {FirstName: "323", LastName: "2323"}, Keys: ["xiaoming", "xiaohong"]},
{UserId: "22", UserName: {FirstName: "323", LastName: "2323"}, Keys: ["xiaoming", "xiaohong"]},
{UserId: "33", 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 and monitor the browser. You can find that the submitted data is the serialized content of the json object:
Copy codeThe Code is 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 % 22 UserId % 22% 3A % 2211% 2C % 22 Name % 22% 3A % 7B % 22 FirstName % 22% 3A % 22% 2C % 22 LastName % 22323% 3A % 222323% 22% 7D % 2C % 22 Keys % 22% 3A % 5B % 22 xiaoming % 22% 2C % 22 xiaohong % 22% 5D % 7D % 2C % 7B % 22 UserId % 22% 3A % 2222% 22% 2C % 22 Name % 22% 3A % 7B % 22 FirstName % 22% 3A % 22323% 2C % 22 LastName % 22% 3A % 22% 7D % 2C % 22 Keys % 222323% 3A % 5B % 22 xiaoming % 22% 2C % 22 xiaohong % 22% 5D % 7D % 2C % 7B % 22 UserId % 22% 3A % 2233% 22% 2C % 22 Name % 22% 3A % 7B % 22 FirstName % 22% 3A % 22323% 22% 2C % 22 LastName % 22% 3A % 222323% 7D % 2C % 22 Keys % 22% 3A % 5B % 22 xiaoming % 22% 2C % 22 xiaohong % 22% 5D % 7D % 5D

Second, bind the backend server's processing parameters:
Copy codeThe Code is 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 group </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)
{
// Obtain 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 submit 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 obtains the data returned by the backend. The result is the data submitted by the user:

The Newtonsoft. json component is used for background Json deserialization. For more information, see: http://james.newtonking.com/

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.