将JSON发布到API Conroller并不会绑定到c#模型

时间:2015-04-30 11:51:58

标签: c# json asp.net-mvc angularjs

我已经查看了很多帖子,但我看不出我做错了什么。我怀疑有一个小问题,我已经失明了。我希望有人能指出我正确的方向。

我有一个采用HTTPPost的API控制器,我有一个使用AngularJS控制器的视图。

我遇到的问题是我可以看到使用Fiddler发布的请求。但是,带有Invoice参数的API控制器似乎正在接收null。我已经在这里检查了其他帖子,虽然我发现了类似的问题,但我还没有找到实施中的错误。

任何想法?代码如下......

模型如下;

    [Serializable]
public class Invoice
{
    [JsonProperty(PropertyName = "invoiceId")]
    public Guid InvoiceId { get; set; }

    [JsonProperty(PropertyName = "customer")]
    public Customer Customer { get; set; }

    [JsonProperty(PropertyName = "productDetails")]
    public Product ProductDetails { get; set; }
}

[Serializable]
public class Product
{
    [JsonProperty(PropertyName = "product")]
    public string ProductName { get; set; }
}

[Serializable]
public class Customer
{
    [JsonProperty(PropertyName = "customerID")]
    public Guid CustomerId { get; set; }
    [JsonProperty(PropertyName = "firstName")]
    public string Firstname { get; set; }
    [JsonProperty(PropertyName = "lastName")]
    public string Lastname { get; set; }
    [JsonProperty(PropertyName = "address1")]
    public string Address1 { get; set; }
    [JsonProperty(PropertyName = "address2")]
    public string Address2 { get; set; }
    [JsonProperty(PropertyName = "town")]
    public string Town { get; set; }
    [JsonProperty(PropertyName = "county")]
    public string County { get; set; }
    [JsonProperty(PropertyName = "postCode")]
    public string PostCode { get; set; }
}

AngularJS控制器如下;

// define angular module/app
var formApp = angular.module('invoice', [])
.controller('invoiceCtrl', function ($scope, $http) {

$scope.invoiceDetails = {
    invoiceId: "fbd7fe22-81b1-4886-8d0e-13be442b8444",
    customer: {
        firstName: "Joe",
        lastName: "Bloggs",
        address1: "1 Somewhere",
        address2: "",
        town: "Oxford",
        county: "OXON",
        postCode: "OX26 5TY"
    },
    productDetails: {
        product:"prod name"
    }
}



// process the form
$scope.processForm = function () {

    $http.post(
        '/api/invoice', 
        JSON.stringify($scope.invoiceDetails),
        {
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            }
        }


    )
    .success(function (data) {
        console.log(data);

        if (!data.success) {
            // if not successful, bind errors to error variables
            $scope.errorFirstName = data.errors.firstname;
            $scope.errorLastName = data.errors.lastName;
        } else {
            // if successful, bind success message to message
            $scope.message = data.message;
        }
    });
};

});

发布细节的观点如下;

<div ng-app="invoice" ng-controller="invoiceCtrl">

    <h2 class="content-margin">Create Invoices using this page</h2>

    <h5 class="content-margin">Invoice ID </h5><span ng-model="invoiceDetails.invoiceId"></span>

    <form class="form-horizontal" ng-submit="processForm()">
        <h4>Customer Details</h4>
        <div class="form-group">
            <label for="Forename" class="control-label col-xs-2">Customer Forename:</label>
            <div class="col-xs-10 col-md-6 col-lg-5">
                <input type="text" class="form-control" id="Forename" placeholder="" ng-model="invoiceDetails.customer.firstName">
            </div>
        </div>
        <div class="form-group">
            <label for="Surname" class="control-label col-xs-2">Customer Surname:</label>
            <div class="col-xs-10 col-md-6 col-lg-5">
                <input type="text" class="form-control" id="Surname" placeholder="" ng-model="invoiceDetails.customer.lastName">
            </div>
        </div>
        <div class="form-group">
            <label for="AddressLine1" class="control-label col-xs-2">Address Line 1:</label>
            <div class="col-xs-10 col-md-6 col-lg-5">
                <input type="text" class="form-control" id="AddressLine1" placeholder="" ng-model="invoiceDetails.customer.address1">
            </div>
        </div>
        <div class="form-group">
            <label for="AddressLine2" class="control-label col-xs-2">Address Line 2:</label>
            <div class="col-xs-10 col-md-6 col-lg-5">
                <input type="text" class="form-control" id="AddressLine2" placeholder="" ng-model="invoiceDetails.customer.address2">
            </div>
        </div>
        <div class="form-group">
            <label for="City" class="control-label col-xs-2">City:</label>
            <div class="col-xs-10 col-md-6 col-lg-5">
                <input type="text" class="form-control" id="City" placeholder="" ng-model="invoiceDetails.customer.town">
            </div>
        </div>
        <div class="form-group">
            <label for="County" class="control-label col-xs-2">County:</label>
            <div class="col-xs-10 col-md-6 col-lg-5">
                <input type="text" class="form-control" id="County" placeholder="" ng-model="invoiceDetails.customer.county">
            </div>
        </div>
        <div class="form-group">
            <label for="PostCode" class="control-label col-xs-2">Post Code:</label>
            <div class="col-xs-10 col-md-6 col-lg-5">
                <input type="text" class="form-control" id="PostCode" placeholder="" ng-model="invoiceDetails.customer.postCode">
            </div>
        </div>

        <input type="submit" name="Submit" value="Submit" class="btn btn-success btn-large" />

</form>

</div>

修改

被调用的控制器动作如下;

[HttpPost]
public async Task<HttpResponseMessage> Post([FromBody]Invoice invoiceDetails)
{
    if (invoiceDetails == null) return this.Request.CreateResponse(HttpStatusCode.BadRequest);

  //  _invoiceRepository.Add(value);

    return this.Request.CreateResponse(HttpStatusCode.OK, new { });
}

帖子如下

    {
    "invoiceId": "fbd7fe22-81b1-4886-8d0e-13be442b8444",
    "customer": {
        "firstName": "Joe",
        "lastName": "Bloggs",
        "address1": "1 Somewhere",
        "address2": "",
        "town": "Oxford",
        "county": "OXON",
        "postCode": "OX26 5TY"
    },
    "product": {
        "productName": "Prod reg"
    }
  }

1 个答案:

答案 0 :(得分:1)

主要问题是模型上的Serializable属性。如果你删除它们一切都会正常工作。如果您需要此属性用于其他一些内容并且无法删除,则可以添加JsonObject属性:

[JsonObject]
[Serializable]
public class Invoice
{
    // Properties
}

不要忘记对从JSON反序列化的所有类执行此操作。

同样在您发布的最后一个JSON示例中,您有carDetails而不是productDetails。我认为这只是一个错字。