在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 }