0

The following simple insert record method works in Postman but I can not get it to work in my AngularJS controller.

Postman Headers (Post)  
Key ContactID  Value 0  
Key FName      Value John  
Key LName      Value Smith  
Key Cache-Control Value no-cache  
Key Content-Type  Value application/x-www-form-urlencoded
$scope.insert = function () {

 var obj = { "ContactID": 0, "FName": "John", "LName": "Smith" };

 var url = "http://********************.net/api/create";

 $http({
     method: 'POST',
     url: url,
     headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
     dataType: 'json',
     contentType: 'application/json',
     data: obj
  });
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • 1
    Do you absolutely need it to be `x-www-form-urlencoded`? You would need to [serialise it](https://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded-form-data-with-http) first. Otherwise it's enough to have `$http.post(url, obj)` – Aleksey Solovey Jul 09 '18 at 13:07
  • My C# Method [System.Web.Http.AcceptVerbs("GET", "POST")] [System.Web.Http.HttpPost] [System.Web.Http.Route("api/Create")] public HttpResponseMessage Create([FromBody] Contact model) { var c = new Contact(); c.FName = model.FName; c.LName = model.LName; repository.Add(c); return new HttpResponseMessage(HttpStatusCode.OK); } If I include x-www-form-urlencoded it inserts a record with blank fields. If I disclude it, not record gets inserted. – Jeff Breuninger Jul 09 '18 at 13:23
  • edit your question to include C# code and add relevant tags – Aleksey Solovey Jul 09 '18 at 13:26
  • Solved $http({ method: 'POST', url: url, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: $.param(dataObj) }); – Jeff Breuninger Jul 09 '18 at 14:35

1 Answers1

0

URL-encoding variables using only AngularJS services

With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with transformRequest or using external dependencies like jQuery:

  1. $httpParamSerializerJQLike - a serializer inspired by jQuery's .param()

  2. $httpParamSerializer - a serializer used by Angular itself for GET requests

Example usage

$http({
  url: 'some/api/endpoint',
  method: 'POST',
  data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
  }
}).then(function(response) { /* do something here */ });
georgeawg
  • 48,608
  • 13
  • 72
  • 95