简体   繁体   中英

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 :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM