T. Ferreira T. Ferreira - 1 year ago 98
AngularJS Question

AngularJS - $http.post keeps sending "NULL" values to ASP.NET Web API 2

In simple terms, I'm making a task management tool with CRUD funcionality using AngularJS for the frontend and ASP.NET for the backend.

In the ASP.NET I've created a table called "KBTM_Task" with the following parameters:

public class KBTM_Task
public int ID { get; set; }
public string KBTM_Task_ID { get; set; } // this is an ID chosen by the user
public string KBTM_Task_Title { get; set; }
public string KBTM_Task_Description { get; set; }

If I had rows to this table, either manually in Visual Studio or with Postman, then I can successfuly display these rows in a table in the frontend app using

The problem is when adding new rows within the app. I have a "New Task" button which takes the user to a form. What I want is for those values filled by the user to be stored in the database and then displayed in the table with the others.

Here's my HTML code:

<div class="form-group row">
<div class="col-xs-12 col-md-6">
<label for="Task_Title">Title</label>
<input type="text" class="form-control" id="Task_Title" ng-model="tasks.title">
<div class="col-xs-6 col-md-3">
<label for="Task_ID">ID</label>
<input type="text" class="form-control" id="Task_ID" ng-model="tasks.id">
<div class="col-xs-6 col-md-3">
<label for="Task_Description">Description</label>
<textarea class="form-control" rows="3" id="Task_Description" ng-model="tasks.description"></textarea>

Here's the Angular code:

$scope.add = function (tasks)
if ($scope.tasks.title != null)
'KBTM_Task_ID': $scope.tasks.id,
'KBTM_Task_Title': $scope.tasks.title,
'KBTM_Task_Description': $scope.tasks.description

var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded'

$http.post('http://localhost/api/KBTM_Task', JSON.stringify($scope.tasks), config)

The problem is that this adds a new row but with all the parameters "NULL". So it successfuly creates a new entry in the database but it doesn't send any of the values that I filled in the form.

You can check my KBTM_TaskController (95% of it was automatically generated by Visual Studio) on this pastebin: http://pastebin.com/HRvgN7Jr

Please help me as I'm completely stuck. If you require more information, don't hesitate to ask. Thank you!

Win Win
Answer Source

Ideally, you want to post data inside body. FYI: Posting data via URL has limitation.

If so, you do not need JSON.stringify and config. $scope.tasks is enough.

Please ensure post data is a single record instead of array.

var data = {
  'KBTM_Task_ID': 'one',
  'KBTM_Task_Title': 'two', 
  'KBTM_Task_Description': 'three' 

$http.post('http://localhost/api/KBTM_Task', data)
  .then(function(response){ console.log(response.data)} );

However, Post action method's parameter binding should be [FromBody] which forces Web API to read a complex type from the request body.

public IHttpActionResult PostKBTM_Task([FromBody] KBTM_Task kBTM_Task)