大发体育娱乐在线-大发体育娱乐官方网站-大发体育娱乐登录网址
做最好的网站

Mvc传递复杂json数据

来源:http://www.dfwstonefabricators.com 作者:关于计算机 人气:95 发布时间:2019-09-19
摘要:调用jQuery的ajax方法时,jQuery会依照post只怕get合同对参数data进行种类化; 举个例子提交的数量运用复杂的json数据,比如: {userId:32323,userName:{firstName:"李",lastName:"李大嘴"}} 那么服务器是力不可

调用jQuery的ajax方法时,jQuery会依照post只怕get合同对参数data进行种类化;

举个例子提交的数量运用复杂的json数据,比如:

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

那么服务器是力不可能及不奇怪接收到一体化的参数,因为jQuery对data的体系化,是采纳了键值对拼装的措施;

参数拼装成 userId=32323&userName=object ; userName所针对的目的被种类化成字符串"object"

什么手艺把三个繁杂的object对象提交到后台的action参数中吗?

先是,化解jQuery对于参数种类化的难点:

复制代码 代码如下:

/*指标连串化为字符串*/
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异步央求:

复制代码 代码如下:

$(function() {
/*按键点击事件*/
$("#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");
});
});

点击开关提交数据,监察和控制浏览器,能够发现提交的数码是json对象的种类化后的剧情:

复制代码 代码如下:

POST /Home/Test HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: zh-cn
Referer:
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

帮忙,后台服务器管理参数绑定:

复制代码 代码如下:

using System.Collections.Generic;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace WebOS.Controllers
{
[HandleError]
public class HomeController : Controller
{
/// <summary>
/// 测验方法
/// </summary>
/// <param name="users">顾客数量</param>
/// <returns>提交的客户数组</returns>
public ActionResult Test([ModelBinder(typeof(JsonBinder<User>))]List<User> users)
{
return Json(users, JsonRequestBehavior.AllowGet);
}
}
/// <summary>
/// 对象实体
/// </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>
/// 对象实体
/// </summary>
[JsonObject]
public class UserName
{
[JsonProperty("FirstName")]
public string FirstName { get; set; }
[JsonProperty("LastName")]
public string LastName { get; set; }
}
/// <summary>
/// Json数据绑定类
/// </summary>
/// <typeparam name="T"></typeparam>
public class JsonBinder<T> : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
//从呼吁中赢得提交的参数数据
var json = controllerContext.HttpContext.Request.Form[bindingContext.ModelName] as string;
//提交参数是指标
if (json.StartsWith("{") && json.EndsWith("}"))
{
JObject jsonBody = JObject.Parse(json);
JsonSerializer js = new JsonSerializer();
object obj = js.Deserialize(jsonBody.CreateReader(), typeof(T));
return obj;
}
//提交参数是数组
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;
}
}
}

后者获取到后台重临的多少,结果就是顾客提交的多寡:
图片 1
后台json反连串化使用了牛顿soft.Json 组件,有关资料请参见:

你也许感兴趣的篇章:

  • SpringMVC落成前端后台交互传递数据
  • ASP.NET MVC从调整器传递数据到视图的八种艺术详解
  • springMVC框架下JQuery传递并剖判Json数据
  • Spring MVC 学习 之 - UENVISIONL参数字传送递详解
  • jsp 展现springmvc modelmap传递的目的详细介绍
  • SpringMVC框架下JQuery传递并分析Json格式的多寡是何许兑现的
  • ASP.NET中MVC传递数据的两种方式总括
  • Ruby on Rails中MVC结构的多少传递深入分析
  • ASP.NET中MVC从后台调整器传递数据到前台湾电视机中心图的主意
  • MVC页面之间参数字传送递深入分析

本文由大发体育娱乐在线发布于关于计算机,转载请注明出处:Mvc传递复杂json数据

关键词:

最火资讯