1

Below is my angular and Web APi Code.In the post method null is getting passed instead of India Angular Code:

HWApp.controller('TestCtrl', function ($scope, $http) {
     $scope.SendData = function (Data)
      {
        $scope.whoo = Data;
        console.log(Data);

        $http({
         url: "api/call/firstCall",
         dataType: 'json',
         method: 'POST',
         data: "India",
          headers: {
          "Content-Type": "application/json"
          }
           }).success(function (response) {
            $scope.whoo = response;
            })
            .error(function (error) {
           alert(error);
            });
        }
      }
    );

Web Api Controller

  public class CallController : ApiController
    {
        [HttpGet]
        public string firstCallGet( )
        {
            return "Get";
        }


        [HttpPost]
        public string firstCall([FromBody] string a)
        {
            return a;
        }
    }
Sajal
  • 4,359
  • 1
  • 19
  • 39
Rohit Sharma
  • 179
  • 1
  • 3
  • 18
  • See this http://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data – mindparse May 29 '16 at 07:19
  • I tried this also data: { data: 'India' } but same null is getting passed. – Rohit Sharma May 29 '16 at 07:20
  • see if this helps: http://stackoverflow.com/questions/30957248/how-to-send-post-in-angularjs-with-multiple-params/30957308#30957308 – Sajal May 29 '16 at 07:23
  • What I have understood so far for complex type **[FromUri]** is required but for the simple type we need **[FromBody]** and here I am using the simple one. In the articel above they are using the complex type. – Rohit Sharma May 29 '16 at 07:30

1 Answers1

0

Your data parameter should be JSON object.

data :{country : "India" }

Define a model class to automatically deserialze into.

Public class CountryViewModel{ Public string Country{get; set;} }

Web Api controller should be as follows

public class CallController : ApiController { [HttpPost] public string FirstCall( CountryViewModel in) { return in.Country; } }

David Chelliah
  • 1,319
  • 1
  • 13
  • 24
  • Property mismatch in CountryViewModel, json returns `country` and model expects `Country`. – Sajal May 29 '16 at 07:40
  • But, is there any way to do it without deserializing ? – Rohit Sharma May 29 '16 at 07:41
  • Normally front-end developers complain about returning capitalized keyname in JSON. So we can add following in the application startup and above code will work as it is. http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx – David Chelliah May 29 '16 at 07:50
  • Check this for alternative, using From body http://stackoverflow.com/questions/13771032/post-string-to-asp-net-web-api-application-returns-null – David Chelliah May 29 '16 at 07:56