WebApi2如何用数组传递Json

时间:2017-04-03 07:43:00

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

我有以下Json数组,我从AngularJS

发送它
{id_fleet: 4177, id_fleetfeature: Array[2]}

var dataFeatures = {
    id_fleet: $scope.id,
    id_fleetfeature: $scope.selectedFeatures
}
$http.put(myUrl + "Fleets/Insert", JSON.stringify(dataFeatures)).then(function () {
    Materialize.toast('Features insertadas correctamente', 3000);
    $scope.refreshData();
});

Web API模型

public class modelFleetFeatures {
    public int id_fleet { get; set; }
    public int[] id_fleetfeature { get; set; }
}

Web API函数

[HttpPut]
[Route("api/Fleets/FleetFeature/Update")]
public HttpResponseMessage updateFleetFeature(List<modelFleetFeatures> data)
{
    var cnt = 0;

    foreach (var item in data)
    {
        db.sp_Fleet_FleetFeaturesDelete(item.id_fleet);
        db.SaveChanges();
    }

    foreach (var item in data)
    {
        db.sp_Fleet_FleetFeaturesInsert(item.id_fleet, item.id_fleetfeature[cnt]);
        db.SaveChanges();
        cnt +=1;
    }

    return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}

Web API中,数据的值始终为空

1 个答案:

答案 0 :(得分:0)

您正在使用JSON发送单个对象,那么为什么要在API操作中期待对象列表? 只需要在api Action中预期单个对象,您将在调用中得到该对象模型,如:

public HttpResponseMessage updateFleetFeature(modelFleetFeatures data)
{
    //do stuff
}

无需在put请求中对json对象进行字符串化。

$http.put(myUrl + "Fleets/Insert", dataFeatures).then(function () {
    Materialize.toast('Features insertadas correctamente', 3000);
    $scope.refreshData();
});