如何将表单数据发布到API控制器

表单数据使用jquery发布:

$.ajax('API/Validate/Customer?column=1&rowid=2&vmnr=3&isik=4', { data: JSON.stringify({ headerData: $("#_form").serializeArray() }), async: false, contentType: "application/json; charset=utf-8", dataType: "json", type: "POST" }); 

它由ASP.NET MVC4 Web API控制器接收validation:

 public class ValidateController : ApiController { public class Body { public Dictionary headerData { get; set; } public Dictionary rowData { get; set; } } public HttpResponseMessage Validate( string id, string column, string rowid, int? vmnr, string isik, [FromBody] Body body, string dok = null, string culture = null, uint? company = null ) { ... 

body.headerData值在控制器中为null。

根据如何在Web API控制器Post方法中接收动态数据的回答

body.headerData必须有表单键。 但是,它是空的。

如何将headerData作为控制器中的键,值对?

Chorme开发人员工具显示正确的json发布在正文中:

 {"headerData":[{"name":"Kalktoode","value":"kllöklö"}, {"name":"Kaal","value":""} ]} 

我试图删除

  public Dictionary rowData { get; set; } 

从课堂上但问题仍然存在。

您的控制器与您发送的内容不匹配

实际上,您的控制器会将身体反序列化为:

 { "headerData": {"someKey":"someValue", "otherKEy":"otherValue"}, "rowData": {"someKey":"someKey"} } 

不是您实际发送的JSON的结构。 你的控制器寻找一个拥有2个成员字体的字体 ,而不是键值对的数组

如果您希望控制器使用键值对的数组

通过键值数组,我的意思是:

 { "headerData": [ { "key": "string", "value": "string" } ], "rowData": [ { "key": "string", "value": "string" } ] } 

您需要将Body对象更新为:

  [HttpPost, Route("test")] public void Test(Body b) { } public class Body { public List> headerData { get; set; } public List> rowData { get; set; } }