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

I am trying to transfer data from AngularJS to ASP.net MVC and always gets zero. Here is my code (only posting the main, 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) }) 

FROM#

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

In JSON.stringify ($ scope.new.JsonCar) I get the following:

"{" Name ":" FIAT 500 "," Description ":" New car "" MaxUserCapacity ": 5," PhotoPath ":" no "}"

What am I doing wrong?

+7
angularjs c # asp.net-mvc angularjs-controller angularjs-directive
source share
2 answers

Pass your object directly as an object, not it. Since this is being transmitted right now, this is a string, not an object that can be properly deserialized.

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

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

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

My assumption is that at some point you randomly deserialize your string into an object. It just saves you this extra step.

+8
source

Remove JSON.stringify, your object is already JSON.

Add the [FromBody] attribute:

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

All Articles