barsaar
barsaar

Reputation: 21

Angular post and web api C#

I've tried to make a contact page using AngularJS and C# controller using Web Api.

I am working on it all the last week without find the correct answer that suits me.

I tried also post thru AJAX, JQUERY and angular.

Controller code:

    [HttpPost, AllowAnonymous]
    [Route("ContactUs")]
    public void Post(ContactUsProperties EmailDetails)
    {
        //Code for sending email to the website owner...
    }

Angular JS Code:

app.controller("ContactController", function ($scope, $http) {



$scope.EmailDetails = {
    Phone: null,
    Email: null,
    Name: null,
    Subject: null,
    Body: null
};

$scope.EmailDetailsArr = [
    $scope.Phone,
    $scope.Email,
    $scope.Name,
    $scope.Subject,
    $scope.Body
];

$scope.EmailDetails = {
    Phone: $scope.Phone,
    Email: $scope.Email,
    Name: $scope.Name,
    Subject: $scope.Subject,
    Body: $scope.Body
};
$scope.CreateEmail = function () {

    console.log($scope.EmailDetails);
    console.log(JSON.stringify($scope.EmailDetails));

    $http({
        method: 'POST',
        url: '/ContactUs',
        data: JSON.stringify($scope.EmailDetail)
    });
}

The routing is working, I know it cause the debugger stops me everytime I click on "Send" button. I tried it as an array, as JSON, as XML, as Everything and the object is still null!, I tried with [FROMBODY] still none.

I will be honest that if it POST require change of Web Api Config so I didn't change..

Please Guys Help Me Solve This Out, Explain Will Accept Happily. Thanks :)

Upvotes: 2

Views: 544

Answers (2)

edo.n
edo.n

Reputation: 2420

$http({
    method: 'POST',
    url: '/ContactUs',
    data: JSON.stringify($scope.EmailDetail) <-- you are missing an 's' at the end
});

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48437

You should use [FromBody] in order to got Parameter Binding.

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter.

In this example, the content type is application/json.

public void Post([FromBody] ContactUsProperties EmailDetails)

Upvotes: 1

Related Questions