[英]Issue while binding the POSTed complex form data from Angular JS to ASP.Net Web API 2
I'm working on some demo examples on how to pass the form data from an Angular Service to a Web API 2 controller POST action. 我正在研究一些演示示例,这些示例如何将表单数据从Angular Service传递到Web API 2控制器POST操作。 But my object is always null on the controller side. 但是我的对象在控制器端始终为null。 Here is how my code looks like 这是我的代码的样子
AngularJS Call to Web API 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'
}
});
The pagingVM is an angular $scope object that contains paging details - SortBy, CurrentPage, ItemsPerPage, SortDesc. pagesingVM是一个有角度的$ scope对象,其中包含分页详细信息-SortBy,CurrentPage,ItemsPerPage,SortDesc。
My Web API POST method 我的Web API POST方法
[HttpPost]
[Route("SearchCustomers")]
public HttpResponseMessage Post(string nameFilter, [FromBody] PagingViewModel pagingVM)
{
if (nameFilter == null)
nameFilter = "";
//Code Implementation
}
The PagingViewModel class 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;
}
}
}
The pagingVM parameter is always coming as default object. pageingVM参数始终作为默认对象出现。 A quick look in the Chrome's network activity shows that all the values are being passed in the request body as the form data. 快速浏览Chrome的网络活动可以发现,所有值都作为表单数据传递到了请求正文中。 If I change the parameter type to FormDataCollection, then I can read the values and build my object but I'm looking to Web API bind the incoming request values for me. 如果将参数类型更改为FormDataCollection,则可以读取值并构建我的对象,但我希望Web API为我绑定传入的请求值。 Am I missing something here? 我在这里想念什么吗?
controller 控制者
[RoutePrefix("api/CustomerSpaSilo")]
public class CustomerSpaSiloController : ApiController
{
[HttpPost]
[Route("SearchCustomers")]
public IHttpActionResult Post(string nameFilter, [FromBody] PagingViewModel pagingVM)
{
if (nameFilter == null)
nameFilter = "";
//Code Implementation
return Ok("Result=" + pagingVM.ToString());
}
}
model 模型
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;
}
}
public override string ToString()
{
return string.Format("PagingViewModel(SortBy='{0}',SortDesc='{1}', CurrentPage='{2}', TotalItems='{3}', ItemsPerPage='{4}')",
SortBy, SortDesc, CurrentPage, TotalItems, ItemsPerPage);
}
}
postman screenshot 邮递员屏幕截图
js client js客户端
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Home</title>
</head>
<body ng-controller="HomeController">
<button ng-click="post()">post</button>
<p>{{status}}</p>
<pre>{{result | json}}</pre>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script>
(function() {
'use strict';
console.trace('js loaded');
angular
.module('app', [])
.factory('api', apiFactory)
.controller('HomeController', HomeController);
function apiFactory($http) {
var svc = {
searchCustomers: searchCustomers
};
return svc;
function searchCustomers(nameField, paging) {
return $http
.post('/api/CustomerSpaSilo/SearchCustomers?nameFilter=' + nameField,
paging,
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}
);
}
}
function HomeController($scope, api) {
console.trace('HomeController');
$scope.status = null;
$scope.result = null;
$scope.post = function () {
var paging = {
SortBy: 'abc',
SortDesc: false,
CurrentPage: 3,
TotalItems: 52,
ItemsPerPage: 10
};
api.searchCustomers('ddd', paging)
.then(function(response) {
$scope.status = 'OK';
$scope.result = response.data;
}, function(reason) {
$scope.status = 'Error';
$scope.result = reason;
});
};
}
})();
</script>
</body>
</html>
chrome screenshot chrome屏幕截图
you should use your $http
service like as - 您应该像这样使用$http
服务-
$http.post(MyApp.rootPath + 'api/CustomerSpaSilo/SearchCustomers?nameFilter=' + nameFilter, pagingVM ).then(function (result) {
//success
}, function (data) {
//faild
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.