0

When I pass JSON data from AngularJS to MVC. I am getting below error.

Http request configuration url must be a string or a $sce trusted object. Received: {"method":"POST","url":"Home/SavePDDetails","datatype":"json","data":{"PD":{"Name":"qqq","Address":"www"}}}

MVC code:

[HttpPost]
public JsonResult SavePDDetails(PDDetailsDTO PD)
{
    new PDDetailsDAL().SavePDDetails(PD);
    return Json(new { Success = true, Message = "Success" });
}

AngularJS code

$scope.Click = function() {
  console.log('clicked');

  $http.post({
    method: 'POST',
    url: 'Home/SavePDDetails',
    datatype: "json",
    data: {
      PD: $scope.PD
    }
  }).success(function(response) {
      console.log('success');
      console.log(response);
  }).error(function(response) {
      console.log('error');
      console.log(response);
  });
}
Govinda Rajbhar
  • 2,926
  • 6
  • 37
  • 62
Pradees
  • 191
  • 1
  • 4
  • 17
  • Can you console the $scope.PD object and add in the question? – Prashant Pimpale Jun 22 '18 at 12:53
  • The `.success` method has been [deprecated and removed from V1.6](https://stackoverflow.com/questions/35329384/why-are-angularjs-http-success-error-methods-deprecated-removed-from-v1-6/35331339#35331339). – georgeawg Jun 22 '18 at 20:26
  • See [AngularJS Error Reference - Error: $http:badreq Bad Request Configuration](https://docs.angularjs.org/error/$http/badreq). – georgeawg Jun 22 '18 at 20:30

2 Answers2

1

If data and url are passed as a properties of the config object, don't use the $http.post method. Simply use $http:

  ̶$̶h̶t̶t̶p̶.̶p̶o̶s̶t̶(̶{̶
  $http({
    method: 'POST',
    url: 'Home/SavePDDetails',
    ̶d̶a̶t̶a̶t̶y̶p̶e̶:̶ ̶"̶j̶s̶o̶n̶"̶,̶
    data: {
      PD: $scope.PD
    }
  })

There is no need to stringify the data as the $http Service does that automatically.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
-1

Try as follow in your function.

Use JSON.stringify() to wrap your json

var parameter = JSON.stringify({PD: $scope.PD});

$http.post('Home/SavePDDetails', parameter).
success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
    console.log(data);
}).
error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});
Govinda Rajbhar
  • 2,926
  • 6
  • 37
  • 62