Reputation: 1
I am trying to pass data as JSON object by $http.Post to webAPI method. In WebAPI method, the parameter of the method is a class object.
It works fine when I test the webAPI method by Postman.But I am not able to pass the JSON object by angular $http.post method-I get null values in the webAPI parameter(in the class object).
Can someone please advise how to fix the issue.i am new to AngularJS.Kindly help.
AngularJS Code
angular.module('Test.Employer')
.controller('EmployerController', ['$scope','headerValue', '$http',
function ($scope, headerValue, $http) {
var ipEmployerDetls = {
EmployerName: "cherokee",
Company: "ABC"
};
$http({
url: "http://localhost:212122/api/Values/PostEmployeeData",
dataType: 'json',
method: 'POST',
data: JSON.stringify(ipEmployerDetls),
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.object = response.data;
})
.error(function (error) {
alert(error.Message);
});
})();
WebAPI
using System.Web.Http;
using AttributeRouting.Web.Http;
namespace webAPITestProject.Controllers
{
[Route("api/Values")]
public class ValuesController : ApiController
{
retrieveEmployeeData empData = new retrieveEmployeeData();
retrieveProductDetails prodDetls = new retrieveProductDetails();
[Route("PostEmployeeData")]
[HttpPost]
public DataTable PostEmployeeData([FromBody] Employer empDetails)
{
DataTable dataTable = new DataTable { TableName = "MyTableName" };
dataTable = empData.getEmployeeData(empDetails);
return dataTable;
}
}
}
NOTE: I get NULL value in empDetails in webAPI method,but when I test the method in Postman,it has value.
Upvotes: 0
Views: 1451
Reputation: 1457
Your routing attributes don't look right for how you've specified your $http API call.
Looks like you want the class-level attribute to be:
[RoutePrefix("api/Values")]
public class ValuesController : ApiController
Which will mean that PostEmployeeData has a route of api/Values/PostEmployeeData.
You'll also need to ensure that your properties in ipEmployerDetls directly map to your Employer class (which you haven't shown), so that model binding works correctly.
Upvotes: 1