Stephen Patten
Stephen Patten

Reputation: 6363

Unable to PUT with Angularjs $http.put, receive Invalid JSON primitive

I have the following service define

app.factory('savedPropertiesService', ['$http', function ($http) {
    var sessionId = $('input[name=SessionGuid]').val();
    var contactId = $('input[name=ContactId]').val();
    var savedPropertiesService = {};

    savedPropertiesService.getSavedProperties = function () {
        return $http.get("/Contact/SavedProperties?sessionGuid="+sessionId+"&contactId=" + contactId);
    };

    savedPropertiesService.refreshSavedProperties = function () {
        return $http.get('/Contact/RefreshSavedProperties?sessionGuid=' + sessionId + '&contactId=' + contactId);
    };

    savedPropertiesService.deleteSavedProperty = function (listingKey) {
        return $http['delete']('/Contact/DeleteSavedProperty?sessionGuid=' + sessionId + '&contactId=' + contactId + '&id=' + listingKey);
    };

    savedPropertiesService.updateSavedProperty = function (prop) {
        return $http.put('/Contact/UpdateSavedProperty/', prop);
    };

    return savedPropertiesService;
}]);

and it is being used in my controller like so

$scope.$watch('items', function (newVal, oldVal) {
    if (_.isEmpty(newVal) || _.isEmpty(oldVal)) return;
    var prop = difference(newVal, oldVal);


    savedPropertiesService.updateSavedProperty(prop)
        .success(function (data) {
            $scope.status = data;
        })
        .error(function (error) {
            $scope.status = 'Unable to update saved properties data: ' + error.message;
        });    
}, true);

and the service endpoint (please don't judge the VB)

<HttpPut()>
Function UpdateSavedProperty(rating As RatingDto) As JsonResult
    Return Json(ControlLibrary.CS.__PropDetails.ContactPropertiesDataFactory.UpdateSavedProperty(rating), JsonRequestBehavior.DenyGet)
End Function

No matter what I do, JSON.stringify or not my mvc3 enpoint is NEVER reached and the frameworks throws an exception. System.ArgumentException: Invalid JSON primitive.

I've even just tried to post a hand crafted object to see if it will make it to the endpoint, all to no avail.

Does anybody have any suggestions on what might be wrong with the code?

Thank you, Stephen

Upvotes: 0

Views: 602

Answers (1)

Stephen Patten
Stephen Patten

Reputation: 6363

Turns out I had defined a global transform for $http and it was using jQuery.param() to encode. Once I removed this it work perfectly.

var app = angular.module('app', ['ui.select2', 'ui.bootstrap'])
    .config(['$httpProvider', function ($httpProvider) {
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
        $httpProvider.defaults.transformRequest = function (data) {
            if (data === undefined) {
                return data;
            }
            return $.param(data);
        };
}]);

Upvotes: 1

Related Questions