Home  >  Article  >  Web Front-end  >  Using jQuery to pass complex json data to asp.net Mvc - ModelBinder_jquery

Using jQuery to pass complex json data to asp.net Mvc - ModelBinder_jquery

WBOY
WBOYOriginal
2016-05-16 18:27:551694browse

When calling jQuery's ajax method, jQuery will serialize the parameter data according to the post or get protocol;

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

{userId:32323, userName:{firstName:"李",lastName:"李大mouth"}}

Then the server cannot receive the complete parameters normally, because jQuery uses key-value pair assembly to serialize data. method;

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


How to submit a complex object object to What about the action parameters in the background?

First, solve jQuery’s problem with parameter serialization:

Copy code The code is as follows:

/*Object serialized to string*/
String.toSerialize = function(obj) {
var ransferCharForJavascript = function(s) {
var newStr = s.replace(
/[x26x27x3Cx3Ex0Dx0Ax22x2Cx5Cx00]/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, 0)).getTime());
}
else if (this.toString != undefined) {
return String.toSerialize(obj);
}
}


jQuery asynchronous request:
Copy code The code is as follows :

$(function() {
/*Button click event*/
$("#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 data and monitor In the browser, you can find that the submitted data is the serialized content of the json object:
Copy the code The 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=[{"UserId":"11","Name":{"FirstName":"323","LastName":"2323"},"Keys":["xiaoming","xiaohong"] },{"UserId":"22","Name":{"FirstName":"323","LastName":"2323"},"Keys":["xiaoming","xiaohong"]},{" UserId":"33","Name":{"FirstName":"323","LastName":"2323"},"Keys":["xiaoming","xiaohong"]}]

Secondly, the background server handles parameter binding:
Copy code The 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
{
///
/// Test method
///

/// < ;param name="users">User data
/// Submitted user array
public ActionResult Test([ModelBinder(typeof(JsonBinder users)
{
return Json(users, JsonRequestBehavior.AllowGet);
}
}
///
// / Object entity
///

[JsonObject]
public class User
{
[JsonProperty("UserName")]
public UserName Name { get; set; }
[JsonProperty("UserId")]
public string UserId { get; set; }
[JsonProperty("Keys")]
public List Keys { get; set ; }
}
///
/// Object entity
///

[JsonObject]
public class UserName
{
[JsonProperty("FirstName")]
public string FirstName { get; set; }
[JsonProperty("LastName")]
public string LastName { get; set; }
}
///
/// Json data binding class
///

/// < ;/typeparam>
public class JsonBinder : 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 submission 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 submission parameter is an array
if (json.StartsWith("[") && json.EndsWith("]"))
{
IList list = new List();
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 background, and the result is the data submitted by the user:
Using jQuery to pass complex json data to asp.net Mvc - ModelBinder_jquery
The background json deserialization uses the Newtonsoft.Json component. For relevant information, please refer to: http://james.newtonking.com/
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn