在jquery的ajax中,如果沒加contentType:"application/json",那么data就應該對應的是json對象,反之,如果加了contentType:"application/json",那么ajax發送的就必須是字符串。
下面便是兩種犯錯的例子:
1>前台ajax多加了contentType:"application/json",data卻錯傳成json對象:
后台處理:(employee該pojo對象里有username和password等String字段)
結果都為null
將contentType去掉后,
后台成功反射出對象:
2>ajax中沒加contentType:"application/json",data卻直接使用了json字符串(和上面的一個道理)
后台情況:
3>第三點是真的有點惡心的一點,找了好久才找到。。
那就是 有些 關鍵的屬性在Mvc層中反射失敗,會導致其他所有屬性都為null
比如上面的joindate對應的pojo是Date,本來input框里的值是 Thu Dec 30 00:00:00 CST 1999 ,傳到后台用Date接收,但是顯然格式不對,於是Date合成出了錯,然后坑爹的就來了,因為這個特殊的屬性反射失敗,Mvc層就將請求打回去然后導致瀏覽器報錯400 bad request ,從而導致其他所有屬性都為null。最后把joindate屬性注釋掉,后台什么屬性的值都收到了。。
補充:我們都知道,不管前台發送的是json字符串還是對象,服務器本質上收到的都是字符流,那么為什么ajax又可以直接傳對象呢?因為不加contentType:"application/json"的時候,發送類型變為默認的application/x-www-form-urlencoded,而這種方式會以鍵值對的形式將對象序列化,所以傳進去的對象實際上還是變成了字符流

1 $.ajax({ 2 url: "/LR_WorkFlowModule/LR_WF_MonitorAndEnquirer/Save", 3 //headers: { __RequestVerificationToken: $.lrToken}, 4 data: { strEntity: JSON.stringify(_data) }, 5 type: "post", 6 dataType: "json", 7 //contentType: 'application/json;charset=UTF-8', 8 success: function (res) { 9 console.log('ISOK'); 10 refreshGirdData(); 11 }, 12 error: function () { 13 console.log('Send Request Fail..'); // 請求失敗時的回調函數 14 } 15 16 });

1 // [HttpPost] 2 // [ValidateAntiForgeryToken] 3 //[AjaxOnly] 4 public ActionResult Save(string strEntity) 5 { 6 LR_WF_MonitorAndEnquirerEntity entity = strEntity.ToObject<LR_WF_MonitorAndEnquirerEntity>(); 7 if (entity == null) 8 return Fail("對象轉換失敗,執行失敗!"); 9 10 11 if (!lR_WF_MonitorAndEnquirerIBLL.IsExist(entity)) 12 { 13 lR_WF_MonitorAndEnquirerIBLL.SaveEntity(null, entity); 14 return Success("保存成功!"); 15 } 16 else 17 { 18 return Fail(string.Format("重復添加數據!")); 19 } 20 21 }