之前寫過一篇文章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傳遞參數(shù)。
對于傳遞單個參數(shù)的情況,假設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中截圖可以看到如下:
傳遞的數(shù)據(jù)是一串Form數(shù)據(jù),根據(jù)命名匹配的原則,也是可以取得數(shù)據(jù)的。
將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 ] ] ),根據(jù)ECMA-262標準stringify 函數(shù)返回的是JSON格式的字符串。它可以有3個參數(shù)。摘抄如下:
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根據(jù)命名匹配也是可以獲得到參數(shù)的值。
將將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會自動的被轉(zhuǎn)換成查詢字符串格式key1=value1&key2=value2這種形式,很顯然這種形式不是json格式,因此會出錯。
要避免轉(zhuǎn)換成查詢字符串格式,只需要設置processData為fasle即可。processData默認是true。
這里需要注意的是:當指定了contentType的時候,數(shù)據(jù)將不再按照Form Data的形式提交了,而是變成Request Data的形式提交。可以從圖上的Request Header中看出。需要注意的是,Form Data提交的數(shù)據(jù)可以由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文本,因此根據(jù)命名匹配,就能獲得值了。
對于較為簡單是數(shù)據(jù)類型,有時候不指定contentType也能通過命名匹配傳值。但是對于稍微復雜點的數(shù)據(jù)類型,有時指定contentType: 'application/json',處理起來更加方便。
如果一個controller里的action方法是接受一個List類型的參數(shù),比如:
public ActionResult ReadPersons(List<PersonModel> model)
那么js中先構造這樣的一個json對象的數(shù)組。如下
var ?persons?=?[{?????????????????id:?"001" ,? ????????????????name:?"zhangsan" ,? ????????????????age:?"20" ,? ????????????????gender:?true ,? ????????????????city:?"shanghai" ? ????????????},? ????????????{? ????????????????id:?"002" ,? ????????????????name:?"lisi" ,? ????????????????age:?"21" ,? ????????????????gender:?false ,? ????????????????city:?"beijing" ? ????????????}? ????????????];? 單純一個數(shù)組傳遞是作為data傳遞是,Form Data也是無法識別出的。因此把這個數(shù)組再次組成一個json形式。如下:其中json的鍵值用model是為了能和controller中的參數(shù)名相同,可以匹配。?
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的方式傳遞的,
可以從截圖中看到。但是這種格式的數(shù)據(jù),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格式的數(shù)據(jù),如下:
var ?option?=?{?????url:?'/test/ReadPersons' ,? ????type:?'POST' ,? ????data:?jsonp,? ????dataType:?'html' ,? ????contentType:?'application/json' ,? ????success:?function ?(result)?{?alert(result);?}? };? 因為jquery的ajax方法會把data轉(zhuǎn)換成查詢字符串,因此就變成如下的樣子。這串文本當然不符合json格式,因此會出現(xiàn)下面的錯誤。
如果設置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數(shù)據(jù)了
最后,此處再演示一個更復雜的參數(shù)類型,以便加深理解。
首先看一下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);? ????????});? 最終,發(fā)送出去的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串后,就能自動的匹配參數(shù)了。具體得到的參數(shù)如下截圖:
總結:
1.不指定contentType的話,默認都是application/x-www-form-urlencoded方式發(fā)送。此時即便發(fā)送的是json格式的數(shù)據(jù),默認情況下,jquery的ajax也會把他轉(zhuǎn)為查詢字符串的形式(可以通過修改ajax參數(shù)修改),以FormData的形式發(fā)送出去。
2.不指定contentType的時候,如果controller中的方法簽名比較簡單,那么即便是FormData形式的數(shù)據(jù)也能由MVC的命名匹配規(guī)則獲取到數(shù)據(jù)。
3.指定contentType為'application/json'時候,發(fā)送的數(shù)據(jù)必須是符合json規(guī)范的字符串。通常,使用 JSON.stringify(jsondata)有較好的可讀性,可以獲得一個json字符串。當然,不是必須的。使用拼接的字符串,只要是符合json規(guī)范的,也是可以發(fā)送的。
4.如果contentType為'application/json'時,發(fā)送的data不是符合json規(guī)范的字符串,則會出錯。
5.通常情況下,盡量指定contentType為'application/json',并且發(fā)送json字符串作為發(fā)送數(shù)據(jù),這樣可讀性更好,并且對于復雜的函數(shù)簽名,也能起到很好的匹配。
新人創(chuàng)作打卡挑戰(zhàn)賽 發(fā)博客就能抽獎!定制產(chǎn)品紅包拿不停!
總結
以上是生活随笔 為你收集整理的再谈Jquery Ajax方法传递到action 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔 推薦給好友。