2014-06-24 137 views
0

我對angular web和ASP.NET web API都很陌生。在角度我從表單獲取值,並嘗試通過發佈請求將其傳遞給服務器,她是angular的代碼。如何通過Angular向ASP.net web API發送發佈請求

app.controller('AddTrnController',['$scope', 'CategoriesService','$http', function($scope, CategoriesService, $http){ 
    $scope.categories =[{}]; 
    $scope.AddTrn = {}; 
    function init(){ 
      CategoriesService.getCategories("1") 
      .success(function(data){ 
       $scope.categories = data; 
      }) 
      .error(function(data, status, headers){alert(status);}); 
     } 
    init(); 

    $scope.change= function(option){ 
     $scope.AddTrn.TrnID = option.CatID; 
     $scope.AddTrn.TrnAccount = 1; 
    }; 


    $scope.UpdateTrans=function(){ 
     alert("21312"); 
     $http({method:"post", 
      url:'http://localhost:18678/api/Transaction', 
      params:"data:$scope.AddTrn"} 
      ).success(function(){alert("succeeded"); 
     }).error(function(){alert("faild");}); 
    }; 

}]); 

她是web API的代碼。

public HttpResponseMessage PostTransaction(String transaction) 
     { 
      if (ModelState.IsValid) 
      { 
       HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, transaction); 
       response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = transaction})); 
       return response; 
      } 
      else 
      { 
       return Request.CreateResponse(HttpStatusCode.BadRequest); 
      } 
     } 

我總是從釣魚者得到失敗的響應,當我在API中創建斷點時,它不會觸發。

回答

1

您正在使用params選項將項添加到查詢字符串,你可能會想使用的數據選項,而不是一個帖子,請嘗試更改代碼如下:

$scope.UpdateTrans=function(){ 
     alert("21312"); 
     $http({method:"post", 
       url:'http://localhost:18678/api/Transaction', 
       data:$scope.AddTrn 
       } 
      ).success(function(){alert("succeeded"); 
     }).error(function(){alert("faild");}); 
    }; 
+0

我想雙方的他們和我得到相同的結果 – MohamedAbbas

+0

@ user2918388你可以在你的瀏覽器中使用開發工具,並轉到網絡選項卡,並粘貼你從請求中獲得的響應?如果你告訴我你正在使用什麼瀏覽器,我可以告訴你如何到達 – MDiesel

+0

我正在使用chrome – MohamedAbbas