DIV CSS 佈局教程網

深入 jQuery Ajax 傳值到 Action:單個物件與集合的補充說明
編輯:JQuery特效代碼     

本文是〈jQuery Ajax 傳值到 Action〉的延伸補充,重點在於釐清 contentType、processData 與 JSON.stringify 之間的關係,並示範如何傳遞單個物件、物件陣列,甚至更複雜的巢狀結構。

Controller 端的方法簽名

public ActionResult ReadPerson(PersonModel model){
    string s = model.ToString();
    return Content(s);
}

public ActionResult ReadPersons(List<PersonModel> model){
    // 遍歷 model 組出結果字串
    return Content(result);
}

其中 PersonModel 定義了 id、name、age、gender、city 等屬性並改寫了 ToString()。

傳遞單個物件

先在前端組出 person 物件並以 Ajax 送出:

var person = { id: "001", name: "zhangsan", age: "20", gender: true, city: "shanghai" };
var option = {
   url: '/test/ReadPerson',
   type: 'POST',
   data: person,
   dataType: 'html',
   success: function (result) { alert(result); }
};
$.ajax(option);

此時資料是以 Form Data 形式送出,靠命名匹配即可取值。

若改用 data: JSON.stringify(person),則會送出 JSON 格式的字串,MVC 依命名匹配一樣能取得值。

關鍵陷阱:contentType 與 processData

jQuery Ajax 預設的 contentType 是 application/x-www-form-urlencoded。若把 contentType 改成 application/json,卻仍傳入未序列化的物件,jQuery 會自動把它轉成查詢字串 key1=value1&key2=value2,這顯然不是合法的 JSON,於是就會出錯。

要避免自動轉換,可將 processData 設為 false(預設為 true)。此外需注意:一旦指定了 contentType,資料就不再以 Form Data 提交,而是變成 Request Data;Form Data 可由 FormCollection 取得,Request Data 則不行。

正確做法是同時指定 contentType 與序列化後的字串:

var option = {
   url: '/test/ReadPerson',
   type: 'POST',
   data: JSON.stringify(person),
   dataType: 'html',
   contentType: 'application/json',
   success: function (result) { alert(result); }
};

傳遞物件集合

當 Action 接收 List 型別時,先在前端組出物件陣列,再包成一個以 model 為 key 的 JSON:

var jsonp = { model: persons };

若不指定 contentType,資料以 Form Data 送出,但這種格式 controller 只能取到 model 的兩個元素,無法取得屬性的值。

正確無誤的方式是 contentType 設為 application/json,並以 JSON.stringify 序列化整個物件陣列:

更複雜的巢狀參數

最後示範一個包含 TestClassB 與 List<TestClassA> 的複合方法簽名,逐步在 JS 中組出巢狀 JSON 結構後送出,Controller 一樣能自動完成匹配。

總結:

1. 不指定 contentType 時預設以 x-www-form-urlencoded 送出,jQuery 會把 JSON 轉為查詢字串。
2. 方法簽名簡單時,即使是 Form Data 也能靠命名匹配取值。
3. 指定 contentType 為 application/json 時,data 必須是合法 JSON 字串,通常用 JSON.stringify 產生。
4. 若 contentType 為 application/json 但 data 不是合法 JSON,就會出錯。
5. 建議盡量指定 application/json 並送出 JSON 字串,可讀性更好,對複雜簽名也能良好匹配。

本文出自「一只博客」博客。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved