Mathiyazhagan
Mathiyazhagan

Reputation: 1429

$http post passing value as null to Asp.Net Web API

I have a ASP.Net web API with one post method. I'm calling the post method from angular js. It is not passing me the data to API POST method, All my properties of my requestData object is null. I'm not sure what is the mistake am doing here. Can anyone help me plz.

API Code

public void Post(RequestData data)
{
.....
}

public class RequestData
{
    PropertyDetail propertyDetails;
    ICollection<Model1> model1s;
    ICollection<Model2> model2s;
    ICollection<Model3> model3;
    ICollection<Model4> model4;
}

Client Code

var requesData = new RequestData();
requesData.model0= $scope.model0;
requesData.model1s= $scope.models;
requesData.model2s= $scope.model2s;
requesData.model3s= $scope.model3s;
requesData.model4s= $scope.model4s;

        $http({
            method: 'POST',
            url: window.apiUrl,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            data: requesData,
        }).then(function (res) {
            console.log('succes !', res.data);
            window.alert("Successfully created");
        }).catch(function (err) {
            debugger;
            console.log('error...', err);
        });

Upvotes: 0

Views: 272

Answers (3)

M Bakardzhiev
M Bakardzhiev

Reputation: 632

You can use angular.toJson:

$http({
        method: 'POST',
        url: window.apiUrl,
        headers: { 'Content-Type': 'application/json' },
        data: angular.toJson(requesData),
    }).then(function (res) {
        console.log('succes !', res.data);
        window.alert("Successfully created");
    }).catch(function (err) {
        debugger;
        console.log('error...', err);
    });  

Also make sure that your properties match.

Upvotes: 0

bresleveloper
bresleveloper

Reputation: 6066

After doing as @Jaky71 says, you can learn how .net expects those objects by calling dummy methods with nulls or whatever you nees to mimic.

.net has a strict parser

Upvotes: 0

Jaky71
Jaky71

Reputation: 162

Probably, your server side couldn't map your parameters correctly. Data type matching is important while post some parameters. You can change your client code like this:

...
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(requestData),
        dataType:'json',
...

Upvotes: 1

Related Questions