Wannabe
Wannabe

Reputation: 596

Pass JSON object to WebApi

I'm trying to post data from my web page to my RegistrationController Api. I see it when I submit the form, but when I hit my breakpoint on the WebApi, the parameter 'pilot' is null. Can someone tell me what I need to do to get the data to pass from the web page over to the Registration ApiController?

I saw this post, but it did not seem to work for me. This post, which was close to my question, mentioned that the model needed to annotated, but still did not work for me.

Button on cshtml page:

<button id="submitRegistration" class="btn btn-lg btn-primary btn-block"  
    type="submit">Submit</button>

Angular RegistrationController:

<script type="text/javascript">
'use strict';

var sampleApp = angular.module('RegistrationApp', []);

sampleApp.controller('RegistrationController', function ($scope, $http) {
    var registrationData = {
        "firstname": $scope.firstname,
        "lastname": $scope.lastname,
        "faaNumber": $scope.faaNumber
    };

    $('#submitRegistration').click(function () {

        registrationData = {
            FirstName: $scope.firstname,
            LastName: $scope.lastname,
            FAANumber: $scope.faaNumber
        };

       // When I hit this debugger, the data is good.
       debugger;
        $.post("api/registration",
                JSON.stringify(registrationData),
                function (value) {
                $('#registrationMessage').append(value);
                },
                "json"
        );
    });
});
</script>

WebApi RegistrationController Class:

public class RegistrationController : ApiController
{
// *********** Pilot is null when the breakpoint hits here ************
public HttpResponseMessage Post([FromBody]PilotModel pilot)     
{
    this.RegisterPilot(pilot);

    var response = Request.CreateResponse<PilotModel>(HttpStatusCode.Created, pilot);

    return response;
}

private string RegisterPilot(PilotModel pilot)
{
    var result = string.Empty;

    ...

    return result;
}
}

Pilot Model:

[DataContract]
public class PilotModel
{
    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [DataMember]
    public string FAANumber { get; set; }
}

Upvotes: 2

Views: 6527

Answers (2)

Shyju
Shyju

Reputation: 218852

Since you want to post the data from your angular code, you should be using $http service, which will take care of setting the proper content type as needed. Looks like you are already injecting the $http service to your controller.

var model = { FirstName: "Shyju",
              LastName: "Happy"
              FAANumber: "3454353"  };

$.http("api/registration",model)
  .then(function(response) {
      var result=response.data;
      console.log(result);
  }, function(response) {
      //error happened. Inform the user
  });

Ideally, you should move http calls to a data service and inject that data service to your angular controller.

If you still want to use jQuery ajax (which i would not recommend) ,you can convert your object to a json string and specify the contentType property to "application/json". This approach will work even if your model has complex navigational properties.

$.ajax({
        type: "POST",
        data :JSON.stringify(model),
        url: "api/registration",
        contentType: "application/json"
    });

Take a look at this answer which covers almost all the use cases of sending data to web api using ajax.

Upvotes: 2

Allen King
Allen King

Reputation: 2516

Will take only one minute, give this a try:

$.post("api/registration",
                registrationData,
                function (value) {
                $('#registrationMessage').append(value);
                },
                "json"
        );

Upvotes: 1

Related Questions