I've generated an array of objects in Angular and I want it to send it to the C# controller. How can I do this?
This is the code for generating the array of objects.
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 });
}
This is the C# controller. How can I pass the array of objects as the second parameter in the 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);
}
Thanks for help!
Assuming your Route
contains the clinicId, in a way similar to this:
[Route("{clinicId:int}")]
Then you need to add a parameter to your controller action using the correct type:
public IHttpActionResult InsertNewProductTotal(int clinicId, [HttpPost] Product[] productsList)
{
var newAttorney = _productSaleLogic.InsertNewProductTotal(clinicId, productsList);
return Created(Request.RequestUri.ToString(), newAttorney);
}
where Product
is a class that represents your javascript object:
public class Product {
public int prodId {get; set;}
public int patientId {get; set;}
//etc.
}
In your angular Controller you have to use the $http
service to post the array of objects to your api endpoint:
$http.post("http://myapihost/myapiPath/" + clinicId, $scope.productsArray)
.then(function (response) {
//ok! do something
}, function (error) {
//handle error
});
Of course, if you are not putting the clinicId
parameter inside your Route
attribute, then you should use the following URI for your $http.post
: "http://myapihost/myapiPath?clinicId=" + clinicId
.
[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);
}
then From angular you can do something like this
$http.post("http://api/products/" + clinicId, $scope.productsArray)
.then(function (response) {
//ok! do something
}, function (error) {
//handle error
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.