Pass Data $http.post From AngularJS and ASP.net MVC gets null

All we need is an easy explanation of the problem, so here it is.

i’m trying to pass data from AngularJS to ASP.net MVC and is always getting null.
Here’s my code (only posting the essential, button, controller and c#:

HTML:

<a class="btn btn-grey btn-lg btn-block" ng-click="AddCar()">Save</a>

Controller

$scope.AddCar = function () {
            $http.post("Cars/AddCar", JSON.stringify($scope.new.JsonCar)).success(function (data) {
                Alert(ok)
            })

c#

public string AddCar(string JsonCar) 
        {
            try
           ....
        }

In JSON.stringify($scope.new.JsonCar) i’m getting this:

“{“Name”:”FIAT 500″,”Description”:”New
car”,”MaxUserCapacity”:5,”PhotoPath”:”none”}”

What i’m doing wrong?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Pass your object directly as an object rather than stringifying it. As it’s being passed right now, it’s a string, not an object that can properly be deserialized.

$http.post("Cars/AddCar", $scope.new.JsonCar).success(function (data) {
            Alert(ok)
        })

Create a Car object that matches your payload. The serializer will handle your JSON object for you.

public Car AddCar(Car car) 
    {
        try
       ....
    }

My assumption is that at some point you are deserializing your string into an object regardless. This just saves you that extra step.

Method 2

Remove the JSON.stringify, your object is already JSON.

Add a [FromBody] attribute:

 public string AddCar([FromBody]string JsonCar) 
    {
        try
       ....
    }

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply