使用jQuery向asp.net Mvc傳遞複雜json資料-ModelBinder篇

來源:互聯網
上載者:User

調用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(
/[\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, 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: 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

其次,後台伺服器處理參數綁定: 複製代碼 代碼如下: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;
}
}
}

前端擷取到後台返回的資料,結果就是使用者提交的資料:

後台json還原序列化使用了Newtonsoft.Json 組件,有關資料請參考:http://james.newtonking.com/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.