如何将对象数组从Angular Front-end传递到C#后端

时间:2016-04-29 13:50:43

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

我在Angular中生成了一个对象数组,我希望它将它发送到C#控制器。我怎么能这样做?

这是用于生成对象数组的代码。

var addObjectToArray = function (id, price, quantity, tax) {
  $scope.element = {
    prodId: id,
    patientId: $state.params.patientId,
    clinicId: $cookies.get("clinicId"),
    user: authService.authentication.userName,
    price: price,
    quantity: quantity,
    tax: tax,
    subtotal: price * quantity,
    total: price * quantity + tax
  };
  $scope.productsArray.push({ product: $scope.element });
}

这是C#控制器。如何将对象数组作为C#Controller中的第二个参数传递?

[HttpPost]
[Route("... the route ...")]
[ResponseType(typeof(int))]
public IHttpActionResult InsertNewProductTotal(int clinicId) // << HOW CAN I GET THE ARRAY OF OBJECTS HERE ??? >>
{
    var newAttorney = _productSaleLogic.InsertNewProductTotal(clinicId, productsList);
    return Created(Request.RequestUri.ToString(), newAttorney);
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

假设您的Route包含clinicalId,其方式与此类似:

[Route("{clinicId:int}")]

然后,您需要使用正确的类型向控制器操作添加参数:

public IHttpActionResult InsertNewProductTotal(int clinicId, [HttpPost] Product[] productsList)
{
    var newAttorney = _productSaleLogic.InsertNewProductTotal(clinicId, productsList);
    return Created(Request.RequestUri.ToString(), newAttorney);
}

其中Product是表示您的javascript对象的类:

public class Product {
    public int prodId {get; set;}
    public int patientId {get; set;}
    //etc.
}

在角度控制器中,您必须使用$http服务将对象数组发布到api端点:

$http.post("http://myapihost/myapiPath/" + clinicId, $scope.productsArray)
    .then(function (response) {
        //ok! do something
    }, function (error) {
        //handle error
    });

当然,如果您没有将clinicId参数放在Route属性中,那么您应该为$http.post使用以下URI:"http://myapihost/myapiPath?clinicId=" + clinicId

答案 1 :(得分:0)

[HttpPost]
[Route("api/products/{clinicId}")]

public IHttpActionResult InsertNewProductTotal(int clinicId,[FromBody]Product[]) // << HOW CAN I GET THE ARRAY OF OBJECTS HERE ??? >>
{
    var newAttorney = _productSaleLogic.InsertNewProductTotal(clinicId, productsList);
    return Created(Request.RequestUri.ToString(), newAttorney);
}

然后从角度你可以做这样的事情

$http.post("http://api/products/" + clinicId, $scope.productsArray)
    .then(function (response) {
        //ok! do something
    }, function (error) {
        //handle error
    })