ajax在mvc3控制器方法中发布数据null

我的一个jquery ajaxpost将post数据发送到我的.NET MVC3控制器方法,但在控制器方法中,数据显示为null。 我有很多其他的ajaxpost几乎使用相同的方法体,它们都工作正常,所以我不确定发生了什么。

Ajaxpost:

$.ajax({ url: '/Entity/Relate', type: 'POST', dataType: 'json', contentType: 'applicaiton/json; charset=utf-8', data: { primaryEntityId: parseInt(entityParentId, 10), relatedEntityId: _createdId }, success: function (data) { //do stuff }, error: function () { // throw error }, complete: function () { //do more stuff } }); 

控制器方法:

 [HttpPost] public int Relate(int primaryEntityId, int relatedEntityId) { return relationshipRepository.Add(primaryEntityId, relatedEntityId); } 

问题是当我打破Relate方法时,primaryEntityId和relatedEntityId为null,即使在Firebug中的post数据中,它也显示已将{primaryEntityId:13,relatedEntityId:486}发布到该方法。

关于为什么post看起来不错,但控制器没有拿起数据的任何建议或想法?

但在控制器方法中,数据显示为null

这是不可能的,因为Int32是一个值类型,.NET中的值类型不能为null 。 您可能意味着它们被分配了默认值。 无论如何。

该问题与您在AJAX请求中设置的contentType参数有关。 您需要删除它,因为您不是发送JSON而是发送标准application/x-www-form-urlencoded请求:

 $.ajax({ url: '/Entity/Relate', type: 'POST', dataType: 'json', data: { primaryEntityId: parseInt(entityParentId, 10), relatedEntityId: _createdId }, success: function (data) { //do stuff }, error: function () { // throw error }, complete: function () { //do more stuff } }); 

如果要发送JSON请求,请定义视图模型:

 public class RelateViewModel { public int PrimaryEntityId { get; set; } public int RelatedEntityId { get; set; } } 

然后让你的控制器将此视图模型作为参数:

 [HttpPost] public int Relate(RelateViewModel model) { return relationshipRepository.Add(model.PrimaryEntityId, model.RelatedEntityId); } 

最后发送一个真正的JSON请求(使用JSON.stringify方法):

 $.ajax({ url: '/Entity/Relate', type: 'POST', dataType: 'json', contentType: 'application/json;charset=utf-8', data: JSON.stringify({ primaryEntityId: parseInt(entityParentId, 10), relatedEntityId: _createdId }), success: function (data) { //do stuff }, error: function () { // throw error }, complete: function () { //do more stuff } });