再談Jquery Ajax方法傳遞到action(補充)_jquery

來源:互聯網
上載者:User

之前寫過一篇文章Jquery Ajax方法傳值到action,本文是對該文的補充
假設 controller中的方法是如下:

複製代碼 代碼如下:

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

public ActionResult ReadPersons(List<PersonModel> model) 
        { 
            string result = ""; 
            if (model == null) return Content(result); 
            foreach (var s in model) 
            { 
                result += s.ToString(); 
                result += "-------------"; 
            }
            return Content(result); 
        }

其中PersonModel定義如下:

複製代碼 代碼如下:

public class PersonModel 
    { 
        public int id 
        { 
            set; 
            get; 
        } 
        public string name 
        { 
            set; 
            get; 
        }

        public int age 
        { 
            set; 
            get; 
        }

        public bool gender 
        { 
            set; 
            get; 
        } 
        public string city 
        { 
            set; 
            get; 
        }

        public override string ToString() 
        { 
            string s = string.Format(@"id:{0} 
name:{1} 
age:{2} 
gender:{3} 
city:{4} 
", id, name, age, gender, city); 
            return s; 
        } 
    }

那麼controller方法分別接受單個model和一個model的List。採用通過ajax傳遞參數。
對於傳遞單個參數的情況,假設js代碼如下:

複製代碼 代碼如下:

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);

從chrome中截圖可以看到如下:

傳遞的資料是一串Form資料,根據命名匹配的原則,也是可以取得資料的。

將option 的代碼改成如下

複製代碼 代碼如下:

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

其中JSON.stringify方法簽名為 stringify ( value [ , replacer [ , space ] ] ),根據ECMA-262標準stringify 函數返回的是JSON格式的字串。它可以有3個參數。摘抄如下:
The stringify function returns a String in JSON format representing an ECMAScript value. It can take three parameters. The first parameter is required. The value parameter is an ECMAScript value, which is usually an object or array, although it can also be a String, Boolean, Number or null. The optional replacer parameter is either a function that alters the way objects and arrays are stringified, or an array of Strings and Numbers that acts as a white list for selecting the object properties that will be stringified. The optional space parameter is a String or Number that allows the result to have white space injected into it to improve human readability.
預設的ContentType的屬性值是"application/x-www-form-urlencoded"
引自http://www.w3.org/TR/html401/interact/forms.html#adef-enctype

看要求標頭的截圖:

因此,傳遞到controller的是一個json字串,MVC根據命名匹配也是可以獲得到參數的值。

將將option 的代碼改成如下

複製代碼 代碼如下:

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

把contentType改成json格式,那麼得到的是出錯的資訊。
雖然person是json對象,但是jquery中的ajax,data會自動的被轉換成查詢字串格式key1=value1&key2=value2這種形式,很顯然這種形式不是json格式,因此會出錯。
要避免轉換成查詢字串格式,只需要設定processData為fasle即可。processData預設是true。
這裡需要注意的是:當指定了contentType的時候,資料將不再按照Form Data的形式提交了,而是變成Request Data的形式提交。可以從圖上的Request Header中看出。需要注意的是,Form Data提交的資料可以由FormCollection獲得到。Request Data方式提交的則不能通過FormCollection獲得。
如果把processData設定為預設值true。

如果把processData設定為false。

以上兩種方式,按照application/json的類型傳給都會失敗,因為json是基於文本的格式,上面兩種方式傳遞的都不是json文本。因此會出錯。

因此,把option改成:

複製代碼 代碼如下:

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

則傳遞的就是json文本,因此根據命名匹配,就能獲得值了。

對於較為簡單是資料類型,有時候不指定contentType也能通過命名匹配傳值。但是對於稍微複雜點的資料類型,有時指定contentType: 'application/json',處理起來更加方便。
如果一個controller裡的action方法是接受一個List類型的參數,比如:
public ActionResult ReadPersons(List<PersonModel> model)
那麼js中先構造這樣的一個json對象的數組。如下

複製代碼 代碼如下:

var persons = [{
                id: "001",
                name: "zhangsan",
                age: "20",
                gender: true,
                city: "shanghai"
            },
            {
                id: "002",
                name: "lisi",
                age: "21",
                gender: false,
                city: "beijing"
            }
            ];

單純一個數組傳遞是作為data傳遞是,Form Data也是無法識別出的。因此把這個數組再次組成一個json形式。如下:其中json的索引值用model是為了能和controller中的參數名相同,可以匹配。

複製代碼 代碼如下:

var jsonp = { model: persons };
           var option = {
               url: '/test/ReadPersons',
               type: 'POST',
               data: jsonp,
               dataType: 'html',
               success: function (result) { alert(result); }
           };

由於未指定contentType,因此是預設的application/x-www-form-urlencoded。此時是按照Form Data的方式傳遞的,

可以從截圖中看到。但是這種格式的資料,controller中只能獲得指定model用2個元素,無法獲得元素中屬性的值。

如果把data改成JSON.stringify(jsonp),如下:   

複製代碼 代碼如下:

var option = {
              url: '/test/ReadPersons',
              type: 'POST',
              data: JSON.stringify(jsonp),
              dataType: 'html',
              success: function (result) { alert(result); }
          };

那麼傳遞過去的Form Data是一串字串,controller跟無法識別出這個東西,因此獲不到值。如果僅僅設定contentType: 'application/json',而傳遞的又不是json格式的資料,如下:

那麼傳遞過去的Form Data是一串字串,controller跟無法識別出這個東西,因此獲不到值。如果僅僅設定contentType: 'application/json',而傳遞的又不是json格式的資料,如下:

複製代碼 代碼如下:

var option = {
    url: '/test/ReadPersons',
    type: 'POST',
    data: jsonp,
    dataType: 'html',
    contentType: 'application/json',
    success: function (result) { alert(result); }
};

因為jquery的ajax方法會把data轉換成查詢字串,因此就變成如下的樣子。這串文本當然不符合json格式,因此會出現下面的錯誤。


如果設定contentType: 'application/json',並且設定data: JSON.stringify(persons),如下:

複製代碼 代碼如下:

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

那麼可以獲得到真正完整的json資料了


最後,此處再示範一個更複雜的參數類型,以便加深理解。
首先看一下Controller中的方法簽名,TestClassB 和一個TestClassA的List。稍顯複雜。

複製代碼 代碼如下:

public ActionResult Fortest(TestClassB TB,List<TestClassA> TA)
        {
            string result = "";
            return Content(result);
        }

再看TestClassA和TestClassB,更顯複雜。但是結構要清晰的話,也不是很難。

複製代碼 代碼如下:

public class TestClassA
    {
       public string a1 { set; get; }
       public List<string> a2 { set; get; }
    }
    public class TestClassB
    {
        public string b1 { set; get; }
        public InnerTestClassC ITCC { set; get; }
        public class InnerTestClassC
        {
            public List<int> c1 { set; get; }
        }
    }

看js代碼:逐步的構造出一個json格式。

複製代碼 代碼如下:

$("#btn").click(function () {
            var jsondata = { TB: {}, TA: [] };
            jsondata.TB.b1 = "b1";
            jsondata.TB.ITCC = {};
            jsondata.TB.ITCC.c1 = new Array(1, 2, 3, 4);
            var ta1 = {};
            ta1.a1 = "a1";
            ta1.a2 = new Array("a", "b", "x", "y");
           var ta2 = {};
            ta2.a1 = "a2";
            ta2.a2 = new Array("a2", "b2", "x2");
            jsondata.TA.push(ta1);
            jsondata.TA.push(ta2);
            var option = {
                url: '/test/Fortest',
                type: 'POST',
                data: JSON.stringify(jsondata),
                dataType: 'html',
                contentType: 'application/json',
                success: function (result) { alert(result); }
            };
            $.ajax(option);
        });

最終,發送出去的json字串如下:
{"TB":{"b1":"b1","ITCC":{"c1":[1,2,3,4]}},"TA":[{"a1":"a1","a2":["a","b","x","y"]},{"a1":"a2","a2":["a2","b2","x2"]}]}
Controller接收到這個json串後,就能自動的匹配參數了。具體得到的參數如下截圖:

總結:

1.不指定contentType的話,預設都是application/x-www-form-urlencoded方式發送。此時即便發送的是json格式的資料,預設情況下,jquery的ajax也會把他轉為查詢字串的形式(可以通過修改ajax參數修改),以FormData的形式發送出去。
2.不指定contentType的時候,如果controller中的方法簽名比較簡單,那麼即便是FormData形式的資料也能由MVC的命名匹配規則擷取到資料。
3.指定contentType為'application/json'時候,發送的資料必須是符合json規範的字串。通常,使用 JSON.stringify(jsondata)有較好的可讀性,可以獲得一個json字串。當然,不是必須的。使用拼接的字串,只要是符合json規範的,也是可以發送的。
4.如果contentType為'application/json'時,發送的data不是符合json規範的字串,則會出錯。
5.通常情況下,盡量指定contentType為'application/json',並且發送json字串作為發送資料,這樣可讀性更好,並且對於複雜的函數簽名,也能起到很好的匹配。

本文出自 “一隻部落格” 部落格

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.