MohamedAbbas
MohamedAbbas

Reputation: 1161

How to send post request through Angular to ASP.net web API

I am new to both angular and ASP.NET web API. in angular i get values from a form and try to pass it to the server through post request her is the code for angular.

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

}]); 

And her the the code for 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);
            }
        }

I always get failed response from angler and when i make breakpoint in API it dose not trigger.

Upvotes: 0

Views: 835

Answers (1)

MDiesel
MDiesel

Reputation: 2667

The params option that you are using adds items to the query string, for a post you will probably want to use the data option instead, try changing the code to this:

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

Upvotes: 1

Related Questions