始终在ajax post的控制器中获取空值
我从我的视图中尝试了一个ajaxpost,如下所示(使用jQuery)。
完整解决方案。
$(document).ready(function () { var kk = { Address1: "423 Judy Road", Address2: "1001", City: "New York", State: "NY", ZipCode: "10301", Country: "USA" }; console.log(JSON.stringify(kk)); $.ajax({ url: 'Check', type: 'POST', data: JSON.stringify(kk), dataType:"json", contentType: 'application/json; charset=utf-8', success: function (data) { alert(data.success); }, error: function () { alert("error"); } }); });
并在控制器中接收它(该方法始终被调用)
public ActionResult Check(AddressInfo addressInfo) { return Json(new { success = true }); }
在这里建模,但是当我试图访问(断点检查)对象( AddressInfo
)的属性时,它总是显示null
值。 我试过没有字符串化和字符串化。 我现在正在学习MVC和初学者。 请帮忙
这是不起作用的原因是因为你使用ASP.NET MVC 2并且直到ASP.NET MVC 3才添加对JSON模型绑定的支持。
您可以将该function添加到ASP.NET MVC 2中。 Phil Haack有一篇文章描述了这一点,最后提供了示例代码的链接: http : //haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-方法-argument.aspx
请尝试以下代码:
return this.Json(new { success = true }, JsonRequestBehavior.AllowGet);
如果这不起作用,只需将请求参数从AddressInfo
更改为控制器端的String。 这绝对有用!!
尝试以查询字符串方式传递数据,如下所示:
$(document).ready(function () { var data = "Address1=423 Judy Road&Address2=1001&City=New York&State=NY&ZipCode=10301&Country=USA"; $.ajax({ url: 'Check', type: 'POST', data: data, contentType: 'application/json; charset=utf-8', success: function (data) { alert(data.success); }, error: function () { alert("error"); } }); });
在Ajax
addressInfo
dataType
添加为json
,并在data parameter
传递addressInfo
,如,
$.ajax({ url: 'Check', type: 'POST', datatype:'json', data: {addressInfo:kk}, success:function(data){ .... .... });