简体   繁体   English

从Angular JS将POST的复杂表单数据绑定到ASP.Net Web API 2时出现问题

[英]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.

相关问题 ASP.NET Web API 不接收从 Angular 发布的数据 - ASP.NET Web API does not receive the data posted from Angular 使用x-www-form-urlencoded发布数据的ASP.Net Web API自定义模型绑定 - 似乎没什么用 - ASP.Net Web API custom model binding with x-www-form-urlencoded posted data - nothing seems to work 无法使用 Angular 从 asp.net 获取发布的数据 - Unable to get posted data with Angular from asp.net Angular 4-如何从ASP.Net Web API获取数据 - Angular 4 - How to get data from ASP.Net web api 从角度4发布的数据在.net Core Web API中获取为空 - Data that is posted from angular 4 is getting as null in .net core web api 发生绑定错误时,ASP.NET MVC 3会将发布的表单数据保留在表单中 - ASP.NET MVC 3 keep posted form data in form when there are binding errors 具有集合属性的类在作为 XML 发布到 ASP.Net Core 3.1 Web API 时未正确绑定 - Class with Collection Properties are not binding properly when posted as XML to ASP.Net Core 3.1 Web API ASP.NET MVC 4 RC Web API参数绑定问题 - ASP.NET MVC 4 RC Web API Parameter Binding Issue ASP.NET WEB API中的模型绑定问题 - Model binding issue in ASP.NET WEB API ASP.NET WEB API 2中的复杂对象 - Complex object in ASP.NET WEB API 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM