gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:59:47 25 4
gpt4 key购买 nike

我在 Angular 中生成了一个对象数组,我希望它将它发送到 C# Controller 。我该怎么做?

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

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# Controller 。如何将对象数组作为第二个参数传递到 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);
}

感谢您的帮助!

最佳答案

假设您的 Route包含 clinicId,其方式类似于:

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

然后您需要使用正确的类型向您的 Controller 操作添加一个参数:

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

在您的 Angular Controller 中,您必须使用 $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 .

关于c# - 如何将对象数组从 Angular 前端传递到 C# 后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36940135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com