[angularjs] How to send POST in angularjs with multiple params?

I want to send multiple parameters using angularjs HTTP post service.

Here is client side code:

$http.post("http://localhost:53263/api/Products/", [$scope.product, $scope.product2]).
        then(function (data, status, headers, config) { alert("success") },
             function (data, status, headers, config) { alert("error") });

Here is server side code:

// POST api/<controller>
public void Post([FromBody]Product product,[FromBody]Product product2)
{
    var productRepository = new ProductRepository();
    var newProduct = productRepository.Save(product);
}

But when I make the post I get error. Any idea what I am doing wrong?

This question is related to angularjs

The answer is


Client Side

Data needs to be grouped in an object array as payload - Indata:

var Indata = {'product': $scope.product, 'product2': $scope.product2 };

Pass the payload through $http.post as the second argument:

$http.post("http://localhost:53263/api/Products/", Indata).then(function (data, status, headers, config) { 
    alert("success"); 
},function (data, status, headers, config) { 
    alert("error"); 
});

Server Side

Create a Data Transfer Object(DTO) class as such:

public class ExampleRequest {
   public string product {get; set;};
   public string product2 {get; set;};
}

The class below accepts DTO with the same property names which the payload is carrying.

public void Post(ExampleRequest request)
{
    var productRepository = new ProductRepository();
    var newProduct = productRepository.Save(request.product);
}

In above class, request contains 2 properties with values of product and product2


You can only send 1 object as a parameter in the body via post. I would change your Post method to

public void Post(ICollection<Product> products)
{
}

and in your angular code you would pass up a product array in JSON notation


import { HttpParams} from "@angular/common/http";
let Params= new HttpParams();
Params= Params.append('variableName1',variableValue1);
Params= Params.append('variableName2',variableValue2);

http.post<returnType>('api/yourApiLocation',variableValue0,{headers, params: Params})

  var headers = {'SourceFrom':'web'};
  restUtil.post(url, params, headers).then(function(response){

You can also send (POST) multiple params within {} and add it.


var name = $scope.username;
var pwd = $scope.password;

var req = {
    method: 'POST',
    url: '../Account/LoginAccount',
    headers: {
        'Content-Type': undefined
    },
    params: { username: name, password: pwd }
}

$http(req).then(function (responce) {
    // success function
}, function (responce) {
    // Failure Function
});

It depends on what is your backend technology. If your backend technology accepting JSON data. data:{id:1,name:'name',...}

otherwise, you need to convert your data best way to do that creating Factory to convert your data to id=1&name=name&...

then on $http define content-type. you can find full article @https://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: {username: $scope.userName, password: $scope.password}
}).success(function () {});

ref:How do I POST urlencoded form data with $http in AngularJS?

!important about encodeURIComponent(obj[p]) will transfer object the way implicit. like a date value will be converted to a string like=>'Fri Feb 03 2017 09:56:57 GMT-0700 (US Mountain Standard Time)' which I don't have any clue how you can parse it at least in back-end C# code. (I mean code that doesn't need more than 2-line) you can use (angular.isDate, value.toJSON) in date case to convert it to more meaningful format for your back-end code.

I'm using this function to comunicating to my backend webservices...

 this.SendUpdateRequest = (url, data) => {
            return $http({
                method: 'POST',
                url: url,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                transformRequest: function (obj) { return jsontoqs(obj); },
                data: { jsonstring: JSON.stringify(data) }
            });
        }; 

and bellow code to use it...

webrequest.SendUpdateRequest(
  '/Services/ServeicNameWebService.asmx/Update',
  $scope.updatedto)
  .then(
      (res) => { /*/TODO/*/ },
      (err) => { /*/TODO/*/ }
);

in backend C# I'm using newtonsoft for deserializing the data.


add the transformRequest as below to send multiple params to backend

var jq = jQuery.noConflict();
            var transform = function(data) {
                return jq.param(data);
            };
            var config = {
                headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },transformRequest: transform
            };

      var params={
            blogPostJson:JSON.stringify($scope.blogPost),
            publish:$scope.blogPost.active
        };
        var url = "${createLink(controller : 'cms', action : 'saveBlog')}";
            $http.post(url,params, config).then(function onSuccess(response) {
                var data = response.data;
               // var status = response.status;
                if (data.error) {
                    alert('error :' + data.error);
                } else {
                  //  alert('Success');

                }

            }).catch(function onError(response) {
                //console.log ("Unable to save Alcohol information");
            });

Here is the direct solution:

// POST api/<controller>
[HttpPost, Route("postproducts/{product1}/{product2}")]
public void PostProducts([FromUri]Product product, Product product2)
{
    Product productOne = product; 
    Product productTwo = product2; 
}

$scope.url = 'http://localhost:53263/api/Products/' +
                 $scope.product + '/' + $scope.product2
$http.post($scope.url)
    .success(function(response) {
        alert("success") 
    })
    .error(function() { alert("fail") });
};

If you are sane you do this:

var $scope.products.product1 = product1;
var $scope.products.product2 = product2;

And then send products in the body (like a balla).


You can also send (POST) multiple params within {} and add it.

Example:

$http.post(config.url+'/api/assign-badge/', {employeeId:emp_ID,bType:selectedCat,badge:selectedBadge})
    .then(function(response) {
        NotificationService.displayNotification('Info', 'Successfully Assigned!', true);
    }, function(response) {
});

where employeeId, bType (Badge Catagory), and badge are three parameters.


If you're using ASP.NET MVC and Web API chances are you have the Newtonsoft.Json NuGet package installed.This library has a class called JObject which allows you to pass through multiple parameters:

Api Controller:

public class ProductController : ApiController
{
    [HttpPost]
    public void Post(Newtonsoft.Json.Linq.JObject data)
    {
        System.Diagnostics.Debugger.Break();

        Product product = data["product"].ToObject<Product>();
        Product product2 = data["product2"].ToObject<Product>();

        int someRandomNumber = data["randomNumber"].ToObject<int>();
        string productName = product.ProductName;
        string product2Name = product2.ProductName;
    }
}

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

View:

<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);
    myApp.controller('controller', function ($scope, $http) {

        $scope.AddProducts = function () {
            var product = {
                ProductID: 0,
                ProductName: "Orange",
            }

            var product2 = {
                ProductID: 1,
                ProductName: "Mango",
            }

            var data = {
                product: product,
                product2: product2,
                randomNumber:12345
            };

            $http.post("/api/Product", data).
            success(function (data, status, headers, config) {
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });
        }
    });
</script>
<div ng-app="app" ng-controller="controller">
    <input type="button" ng-click="AddProducts()" value="Get Full Name" />
</div>