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. But my object is always null on the controller side. Here is how my code looks like

AngularJS Call to 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.

My Web API POST method

[HttpPost]
        [Route("SearchCustomers")]
        public HttpResponseMessage Post(string nameFilter, [FromBody] PagingViewModel pagingVM)
        {
            if (nameFilter == null)
                nameFilter = "";

            //Code Implementation
        }

The PagingViewModel class

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. 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. 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. Am I missing something here?

enter image description here

Related posts

Recent Viewed