gpt4 book ai didi

c# - mvc3 Controller 方法中的ajax发布数据为空

转载 作者:太空宇宙 更新时间:2023-11-03 21:52:05 26 4
gpt4 key购买 nike

我的一个 jquery ajax 帖子将帖子数据发送到我的 .NET MVC3 Controller 方法,但在 Controller 方法中,数据显示为空。我还有许多其他使用几乎相同方法主体的 ajax 帖子,它们都工作正常,所以我不确定发生了什么。

Ajax 帖子:

$.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
}
});

Controller 方法:

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

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

关于为什么帖子看起来不错,但 Controller 没有获取数据有什么建议或想法吗?

最佳答案

but at the controller method, the data shows up as 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 请求定义一个 View 模型:

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

然后让你的 Controller 将这个 View 模型作为参数:

[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
}
});

关于c# - mvc3 Controller 方法中的ajax发布数据为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14013024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com