// Server-side Model to bind
public class CurrentPipelineRequest
{
public List<string> Usernames { get; set; }
}
// Controller
[HttpPost]
public HttpResponseMessage CurrentPipelineByMilestone(CurrentPipelineRequest currentPipelineRequest)
{
//.....
}
// Jquery/Ajax
var model = {
'Usernames' : JSON.stringify(["me", "you", "I"])
};
$.ajax({
contentType: 'application/json',
type: 'POST',
url: 'api/Dashboard/CurrentPipelineByMilestone'
data: model,
success: function (data) {
alert('success');
}
});
目前,控制器操作参数“currentPipelineRequest”将为null。
答案 0 :(得分:2)
ASP.NET Web API中的绑定与ASP.NET MVC不完全相同。
但是在ASP.NET Web API中,正文内容被视为只能读取一次的仅向前流。因此,如果在Actions上有复杂的签名,您需要指定参数的预期位置。
如果您从身体获取参数,请将签名更改为:
public HttpResponseMessage CurrentPipelineByMilestone(
[FromBody] CurrentPipelineRequest currentPipelineRequest)
如果您从uri获取参数,请将签名更改为:
public HttpResponseMessage CurrentPipelineByMilestone(
[FromUri] CurrentPipelineRequest currentPipelineRequest)
如果您从uri和body获取参数,请将签名更改为:
public HttpResponseMessage CurrentPipelineByMilestone(
[ModelBinder] CurrentPipelineRequest currentPipelineRequest)
以下是试用implement MVC style binding in Web API的文章。请注意,我自己没有尝试过。
答案 1 :(得分:2)
您需要stringify
整个模型,而不仅仅是Usernames
:
var model = {
Usernames : ["me", "you", "I"]
};
$.ajax({
contentType: 'application/json',
type: 'POST',
url: 'api/Dashboard/CurrentPipelineByMilestone'
data: JSON.stringify(model),
success: function (data) {
alert('success');
});
答案 2 :(得分:0)
这实际上是因为你正在进行POST而不是将你的模型作为JSON对象发送,所以服务无法理解它。
试试这个:
var model = {
'Usernames' : ["me", "you", "I"]
};
var data = JSON.stringify(model);
$.ajax({
contentType: 'application/json',
type: 'POST',
url: 'api/Dashboard/CurrentPipelineByMilestone'
data: data,
success: function (data) {
alert('success');
}
});