2

I have an HTML form which has the following values:

 <input ng-model="person.id"/><br/>
 <input ng-model="person.name" /><br />
 <input ng-model="person.lastname" /><br />
 <button ng-click="callAPI()">Call API</button>

When clicked I call this function

 $scope.callAPI = function () {

    var person = {
        id: $scope.person.id,
        name: $scope.person.name,
        lastname: $scope.person.lastname
    };

    $http.post('/api/save/SavePerson', person).success(function (data) {
        $scope.returnValue = data;
    }).error(function (data) {
        $scope.error = "An Error has occured while Saving person! " + data;
        $scope.loading = false;
    });
};

I'm trying to pass it to my SavePerson method within my API as shown here:

    [System.Web.Http.AcceptVerbs("GET", "POST")]
    [System.Web.Http.HttpGet]
    public void SavePerson([FromBody]PersonModel person)
    {
        var dooda = string.Empty;
    }

The PersonModel looks like this :

  public class PersonModel
  {
    public int id { get; set; }
    public string name { get; set; }
    public string lastname { get; set; }
  }

However when I click "CallAPI()" and hit the break point within SavePerson the person model is null?

2 Answers 2

2

You need to post a config object, and put your person as the "data" property.

$http.post('/api/save/SavePerson', {data:person})

This should get it into the body for you.

Sign up to request clarification or add additional context in comments.

1 Comment

Worked, thanks I'll accept the answer in ten minutes,
0

Answer: Never ever read $scope on your controller. This will make things really dificulty to test in the future and will not encapsulate the 'function of the function'. Use this instead:

<button ng-click="callAPI(person)">Call API</button>

On your controller,

$scope.callAPI = function (person) {

and you won't need to populate the person object. To your http request, you tried to access the wrong object. You'll receive a 'response' object that contains a data object. And you may change a bit your code to match the new $http request using .then instead of .success and .error.

$http.post('/api/save/SavePerson', person)

  .then( function (response) { //Called on success.
    $scope.returnValue = response.data;

  }, function (response) {  //Called on error
    $scope.error = "An Error has occured while Saving person! " + response.data;
    $scope.loading = false;
  });

Try this and tell me if it works. :)

Comments

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.