将JSON对象传递给WebApi

时间:2015-12-26 21:54:14

标签: c# angularjs json asp.net-web-api

我试图将数据从我的网页发布到我的RegistrationController Api。我在提交表单时看到它,但是当我在WebApi上点击断点时,参数' pilot'一片空白。有人能告诉我我需要做什么才能将数据从网页传递到Registration ApiController吗?

我看到了这个post,但它似乎对我不起作用。这个post与我的问题很接近,提到该模型需要注释,但仍然不适用于我。

cshtml页面上的按钮:

<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>

Angular RegistrationController:

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;
}
}

WebApi RegistrationController类:

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

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

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

试点模型:

 mystring="something something something schwifty3 something"

2 个答案:

答案 0 :(得分:2)

由于您要发布角度代码中的数据,因此您应该使用$http服务,该服务将根据需要设置正确的内容类型。看起来您已经将$ http服务注入控制器。

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
  });

理想情况下,您应该将http调用移动到数据服务,并将该数据服务注入角度控制器。

如果您仍想使用jQuery ajax(我不建议使用),您可以将对象转换为json字符串并将contentType属性指定为"application/json"。即使您的模型具有复杂的导航属性,此方法也会起作用。

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

查看this answer,其中涵盖了几乎所有使用ajax向web api发送数据的用例。

答案 1 :(得分:1)

只需一分钟,试一试:

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