2017-10-17 58 views
3

我試過使用AngularJS和C#控制器使用Web Api製作聯繫頁面。Angular post和web api C#

我在上週的工作都沒有找到適合我的正確答案。

我試過也通過AJAX,JQUERY和角度。

控制器代碼:

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

角JS代碼:

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) 
    }); 
} 

路由工作,我知道這會導致調試器停止我每次我點擊 「發送」 按鈕。我嘗試了它作爲一個數組,因爲JSON,作爲XML,作爲一切,對象仍然是空的!,我嘗試與[FROMBODY]仍然沒有。

我會說實話,如果它需要POST網絡API配置的變化,所以我並沒有改變..

請專家幫我解決了這一點,解釋會很樂意接受。 謝謝:)

+0

試試這個=>網址:「/聯繫我們/郵報」 – imgprasad

+0

你能告訴我們什麼是你希望你的代碼,這樣做? – Hintham

+0

無需將數據串聯起來。 [$ http服務](https://docs.angularjs.org/api/ng/service/$http)將自動執行此操作。 – georgeawg

回答

1

您應該使用[FromBody]爲了得到Parameter Binding

當參數有[FromBody]時,Web API使用Content-Type標頭 選擇一個格式化程序。

在此示例中,內容類型爲application/json

public void Post([FromBody] ContactUsProperties EmailDetails) 
+0

我讀了關於它和它獲得簡單參數的說法,我想要傳遞包含少量字符串而不是1個字符串的對象。不管我讀到的是什麼,我嘗試過並且沒有奏效... – barsaar

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

該對象仍爲空 – barsaar