0

I am trying to post an object which has some properties and arrays in it. Properties are submitted just fine, but arrays within object are not serialized back in a MVC.NET Controller. In this example page is mapped properly, but array object (locations) is always null in the controller. Any suggestions?

//add some data
$scope.formData = {
 Page: 1,
 Locations: []
};
$scope.formData.Locations.push({
 LocationID: 1,
 LocationType: 1
});
$scope.formData.Locations.push({
 LocationID: 2,
 LocationType: 2
});

//post method
$http({
 method: 'POST',
 url: 'myurl',
 params: $scope.formData,
}).then(function successCallback(
 response) {
 //do something
}, function errorCallback(response) {
 //do something

});

Serverside model

public class SearchAuctionData
{     
    public int Page { get; set; }
    public List<SmallLocation> Locations { get; set; }
}

public class SmallLocation
{
    public short LocationID { get; set; }
    public short LocationType { get; set; }
}

Controller

[HttpPost]
[AllowAnonymous]
public async Task<JsonResult> GetAuctions(SearchAuctionData data)
{
//do somethng
   return Json(result);
}

2 Answers 2

1

This:

$http({
 method: 'POST',
 url: 'myurl',
 params: $scope.formData,

Should be:

$http({
 method: 'POST',
 url: 'myurl',
 data: $scope.formData,

Even better, use a service (make sure to inject it to the controller):

app.factory("MyService", ["$http", function($http){
    return {
        postItem: function(url, item) {
            return $http({
                url: url,
                method: 'POST',
                data: item
            });
        }
    }
}]);

Inside the controller

MyService.postItem('/path/to/c#/controller', $scope.formData).then(successCallback).catch(failureCallback);
Sign up to request clarification or add additional context in comments.

1 Comment

what a oversight by me :D. Replaced params with data and all works fine. Thanks
0

What do you mean by "null in the controller"?

After your POST request ?

Or printing $scope.formData.Locations before POST call and that's null?

2 Comments

in the controller on the server Locations object is always null. It maps only root properties of my model, but not arrays. I've added server side code to my question.
I see @KKKKKKKK found your problem. Just to make sure you don't waste anymore time on that mistake like i already did, POST needs data, but GET needs params, just so you know :P !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.