I have a simple test to try to understand $http.post from AngularJS to ASP.NET WebAPI. The post manages to succeed, but received value on the API appears as null. I have tested this and seen that the $scope object holds a value before being posted.
I have checked all over the place and I see that ASP.NET WebAPI handles posts data in strange ways.
Here is my HTML code for getting the input, Basic.html:
<form name="basicItem" novalidate ng-app="app" ng-controller="ItemCtrl">
<label id="titlelabel" class="required">Title</label>
<input ng-model="item.Title" type="text" id="titlefield" name="Title"
required />
This is the code from ItemController.js, which checks validation and posts (I am using CORS since both of these programs have separate domains):
app.controller("ItemCtrl", ['$scope', '$http', function ($scope, $http) {
$scope.submitForm = function (form) {
if (form.$valid) { //If Title has some value
item = {
"Title": $scope.item.Title, //Set "Title" to the user input
}
alert($scope.item.Title); //This shows that my value is not null
$http.post("http://localhost:50261",
{
testTitle: $scope.item.Title //!!!Probably the problem, sets
}).success(function (result) { //the parameter of API post
alert('Success!');
}).error(function (data) {
alert("Valid but didn't connect");
console.log(data);
})
And this is the code in the API controller, EntryController.cs:
[HttpPost]
public string CreateEntry([FromBody]string testTitle)
{
return testTitle; //returns null!!!
}
I have read about needing [FromBody] and only using 1 simple parameter. Finally I have also seen that I should wrap my post value in quotes or give a leading "=" sign, but both of these methods don't seem to work. Any help or suggestions would be grand.
return "ThisIsATest"
to verify where is the problem and tell us the results. – Orel Eraki Feb 17 '16 at 22:35