我一直在抨击我的大脑以及关于同一主题的各种SO帖子(请参阅JQuery Ajax and Posting multiple complex objects to asp.net MVC Controller,Passing multiple objects to my controller等),但我在收到多个对象时遇到问题从Ajax调用到我的控制器(.NET Core)。我相信我已经设置了我的代码,就像本教程(http://www.dotnetcurry.com/aspnet-mvc/1253/multiple-model-objects-input-controller-action-methods)一样,并且也使用了这里的建议:http://andrewlock.net/model-binding-json-posts-in-asp-net-core/无济于事。
问题:我只能得到第一个但不是第二个要绑定的对象。
控制器方法:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Apply(ApplicationInfoViewModel info, SRAgreementViewModel agreement)
{
if(ModelState.IsValid){
//do stuff. ModelState.IsValid returns false here.
}
}
这是我的JS:
$(function () {
$("#ApplyBAOForm").submit(function (e) {
var jsonObj = $('#ApplyForm').serialize();
var srFormJsonObj = $('#SRForm').serialize();
$.ajax({
url: "ApplyBao/Apply",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: { info: jsonObj, agreement: srFormJsonObj },
type: "POST"
}).done(function (result) {
console.log("Apply success: " + result);
if (result.type === "success") {
//hooray
}
else {
//boo
}
});
});
});
所以这有点奇怪:实际上这里有来自两个独立形式的数据。在提交ApplyForm之前验证SRform数据(它是一个模态),但实际上只是为了使用ApplyForm提交持久性。两种形式的结果序列化对象看起来都是正确且相似的(jsonObj和srFormObj)。
当我点击ModelState.IsValid语句时,它返回false,因为SRAgreement对象基本上是null(使用默认值)。但是,ApplicationInfoViewModel对象正确显示表单中的数据。
我尝试过的其他事情:
这可能是一种更好的方法,但我认为我尝试做的事情应该是可行的。
谢谢!
编辑2:
看来我甚至无法绑定一个JSON对象。我必须要错过一些简单的东西。我已经将它简化为只提交JSON这两个对象中的一个:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Apply([FromBody] ApplicationInfoViewModel info)
{
if (ModelState.IsValid)
{
// do stuff
}
}
JS:
$("#ApplyBAOForm").submit(function (e) {
e.preventDefault();
var jsonObj = ConvertFormToJSON($("#ApplyBAOForm"));
var srFormJsonObj = ConvertFormToJSON($("#SRForm"));
var obj2 = JSON.stringify({ info: jsonObj });
$.ajax({
url: "ApplyBao/Apply",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: obj2,
//data: JSON.stringify(jsonObj),
type: "POST"
}).done(function (result) {
console.log("Apply success: " + result);
}
else {
//show some error message or something
}
});
});
});
现在请求看起来像这样:
Request URL:http://localhost:19194/ApplyBao/Apply
Request Method:POST
Status Code:400 Bad Request
Remote Address:[::1]:19194
Response Headers
view parsed
HTTP/1.1 400 Bad Request
Server: Kestrel
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNccmdiMDA3M1xEb2N1bWVudHNcYmFvYWRtaW5pc3RyYXRpb25cc3JjXEJBT0FkbWluaXN0cmF0aW9uXEFwcGx5QmFvXEFwcGx5?=
X-Powered-By: ASP.NET
Date: Thu, 12 Jan 2017 21:59:27 GMT
Content-Length: 0
Request Headers
view parsed
POST /ApplyBao/Apply HTTP/1.1
Host: localhost:19194
Connection: keep-alive
Content-Length: 580
Pragma: no-cache
Cache-Control: no-cache
Accept: */*
Origin: http://localhost:19194
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://localhost:19194/ApplyBao
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Cookie: .AspNetCore.Antiforgery.l7Q8WGuEtq8=CfDJ8K9L5D4kNnBPrb3_9Hu-w57rjjf751Qf9eh-z57qWmtMA53AB6FXsZ7pbIuLkdP2F6GjA7TGl0Tz7TfACCn3QeFt_uC-BgsYnk3Nd8z0ZA0c90XVEA90NnQOnmVFRu_KF2_2DXV89Jur84rMa-s26nQ
Request Payload
view parsed
{"info":{"HearAboutUsSelectedId":"137","FirstName":"Ron","LastName":"Bud","MiddleName":"","MaidenName":"","Email":"r@test.com","BirthDate":"1900-01-15","Phone":"123456","Fax":"","Street":"1234","City":"Denton","State":"TX","Zip":"12345","Country":"USA","SelectedExamTrack":"BCaBA","SelectedTranscriptSendMethod":"requested","Degree":"Education","SraId":"00000000-0000-0000-0000-000000000000","__RequestVerificationToken":"CfDJ8K9L5D4kNnBPrb3_9Hu-w56wPCITEDVZQo7flUIB70Pu4Q81TlRXa_oI4t8Bleou6l45oHHmUFrKusKofA6Gey-uSgKP7M3L-DrawE1TVJnrDsULHlnOE9ngg9LuyFK6-cylBJ-91h5fmaico-0yrZE"}}
JSON现在看起来像一个合适的JSON对象,但似乎我的公主在另一座城堡里。管道中还有其他东西我没有启用它吗?
更新:
我终于明白了。事实证明AntiForgery令牌导致了 请求失败,如下所述: POSTing complex JSON to ASP.NET Core Controller 暂时取消它可以让我继续前进。谢谢!
答案 0 :(得分:2)
您实际上并没有发送2个对象,而是发送1个包含2个其他对象的对象。这就是这一行,即创建将要发送的单个对象。
data: JSON.stringify( { info: jsonObj, agreement: srFormJsonObj } ), // this is a single object that is created and sent by the http action
您需要在服务器上以相同的方式接收它,并使用单个模型,然后包含您当前使用的2种类型作为方法参数。
型号代码
public class Model{
public ApplicationInfoViewModel Info{get;set;}
public SRAgreementViewModel Agreement {get;set;}
}
控制器代码
public IActionResult Apply([FromBody]Model model)
{
if(ModelState.IsValid){
//do stuff. ModelState.IsValid returns false here.
}
}
错误可能是因为您正在发送url编码数据和json以及json对象。您应该使用其中一个,但不能两者兼而有之。如果查看最新更新,您可以看到为属性info
和agreement
发送的值,它们是表单编码的字符串值。
答案 1 :(得分:1)
我也偶然发现了.NET Core 2.1的问题
似乎只能通过 [FromBody] 属性传递一个参数。 您必须将所有参数汇总在一个对象中。
Ajax调用示例:
var data = {
messageIds: selectedIds,
read: true
};
$.ajax({
url: "@Url.Action("SetMessagesReadFlag", "Message")",
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(data),
cache: false,
error: function(xhr, status, error) {
//do something about the error
alert(error);
},
success: function(response) {
if (response != null) {
grid.refresh();
}
}
});
带有虚拟助手类的控制器动作:
[HttpPost]
public IActionResult SetMessagesReadFlag([FromBody] Dummy data)
{
....
return Json(true);
}
public class Dummy
{
public List<Guid> MessageIds { get; set; }
public bool Read { get; set; }
}