表单数据使用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控制器验证:
public class ValidateController : ApiController
{
public class Body
{
public Dictionary<string, string> headerData { get; set; }
public Dictionary<string, string> 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值为空。
根据How to receive dynamic data in Web API controller Post method中的答案
body.headerData必须有表单键。然而,它是空的。
如何在控制器中获取headerData作为密钥、值对?
Chorme developer工具显示,适当的json发布在正文中:
{"headerData":[{"name":"Kalktoode","value":"kllöklö"},
{"name":"Kaal","value":""}
]}
我试着把
public Dictionary<string, string> rowData { get; set; }
但问题依然存在。
发布于 2016-03-24 18:53:47
您的控制器与您要发送的内容不匹配。
实际上,您的控制器将反序列化主体,例如:
{
"headerData": {"someKey":"someValue", "otherKEy":"otherValue"},
"rowData": {"someKey":"someKey"}
}
它是,而不是,它是您实际发送的JSON的结构。您的控制器寻找一个具有两个成员( Dictionnaries,,,,而不是数组的键值对)的主体。
如果您希望您的控制器处理键值对数组
通过键值数组,我的意思是:
{
"headerData": [
{
"key": "string",
"value": "string"
}
],
"rowData": [
{
"key": "string",
"value": "string"
}
]
}
您需要将Body对象更新为:
[HttpPost, Route("test")]
public void Test(Body b)
{
}
public class Body
{
public List<KeyValuePair<string,string>> headerData { get; set; }
public List<KeyValuePair<string,string>> rowData { get; set; }
}
https://stackoverflow.com/questions/36206340
复制相似问题