【发布时间】:2016-04-12 13:30:43
【问题描述】:
我正在编写一些演示示例,说明如何将表单数据从 Angular 服务传递到 Web API 2 控制器的 POST 操作。但我的对象在控制器端始终为空。这是我的代码的样子
AngularJS 调用 Web API
$http({
method: 'POST',
url: MyApp.rootPath + 'api/CustomerSpaSilo/SearchCustomers?nameFilter=' + nameFilter,
data: $.param({ '': pagingVM }),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
pagingVM 是一个角度 $scope 对象,其中包含分页详细信息 - SortBy、CurrentPage、ItemsPerPage、SortDesc。
我的 Web API POST 方法
[HttpPost]
[Route("SearchCustomers")]
public HttpResponseMessage Post(string nameFilter, [FromBody] PagingViewModel pagingVM)
{
if (nameFilter == null)
nameFilter = "";
//Code Implementation
}
PagingViewModel 类
public class PagingViewModel
{
public string SortBy { get; set; }
public bool SortDesc { get; set; }
public int CurrentPage { get; set; }
public int TotalItems { get; set; }
public int ItemsPerPage { get; set; }
public int TotalPages
{
get {
if (this.ItemsPerPage > 0)
return (int)Math.Ceiling((decimal)TotalItems / this.ItemsPerPage);
else
return 1;
}
}
}
pagingVM 参数始终作为默认对象出现。快速浏览一下 Chrome 的网络活动表明所有值都作为表单数据在请求正文中传递。如果我将参数类型更改为 FormDataCollection,那么我可以读取这些值并构建我的对象,但我希望 Web API 为我绑定传入的请求值。我在这里错过了什么吗?
【问题讨论】:
-
我很确定这个 '': pagingVM 应该读取 'pagingVM': pagingVM
-
@Kell 我也尝试过,但无济于事。事实上,这就是我最初尝试的方式。在 chrome 网络选项卡中,它显示为 pagingVM[SortBy]:CustomerID 等。我想知道它周围的方括号是否是问题所在。
-
你可能也想要 JSON.stringify($.param({ 'pagingVM': pagingVM }))。
-
@Kell - 有效的是数据:$.param(pagingVM)。
-
酷,很高兴你把它分类了 :)
标签: c# asp.net angularjs http-post asp.net-web-api2