AngularJS $ http.post for ASP.NET Web API controller with a simple type argument

I have a simple test to try to understand $ http.post from AngularJS to ASP.NET WebAPI. The post succeeds, but the resulting value in the API looks like null. I checked this and saw that the $ scope object is relevant before submitting.

I checked all the places and I see that ASP.NET WebAPI processes message data in strange ways.

Here is my HTML for input 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 that checks validation and messages (I use 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!!!
}

[FromBody] . , , "=", , , . .

+4
2

bluetoft, , WebAPI .

[FromBody], =value POST JSON. .

, , :

    $http.post(urlTest, '"' + $scope.item.Title +'"').success(function(result) { 
        alert('Success!');
    }).error(function(data) {
        alert("Error!");
    });

, , "Your Title", Your Title, .

+3

.NET web api . JSON.stringify . :

 $http.post("http://localhost:50261",
      JSON.stringify({
      testTitle: $scope.item.Title       
      })).success(function (result) {     //the parameter of API post
           alert('Success!');            
      }).error(function (data) {
           alert("Valid but didn't connect");
      console.log(data);
      })
0

Source: https://habr.com/ru/post/1629265/


All Articles