Kurkula
Kurkula

Reputation: 6762

Passing value from angular to webapi put method

I am trying to pass id value from angular code to asp.net web api. I tried couple of ways but still unable to pass the value. What may be the code issue?

Angular Service code

angular.module('myServiceApp')
.factory('mySvc', ['$http', function ($http) {
    return {
        startJob: function (id) {
            return $http.put('/api/Job/Put/' + id);
        }
    };
}]);

HTML Code

<div ng-click="initiateJob(id)">
Start Now
</div>

Angular Function

$scope.initiateJob = function (id) {
    mySvc.startJob(id)
         .success(function () {
             alert('started successfully');
         }).error(function (err) {
             $scope.error = err;                
         });
}

webapi code

public HttpResponseMessage Put(int id)
{
    HttpResponseMessage response = null;           
    return response;
}

Upvotes: 2

Views: 1843

Answers (1)

Denys Wessels
Denys Wessels

Reputation: 17039

Try changing this line:

return $http.put('/api/Job/Put/' + id);

Into this:

return $http.put('/api/Job/' + id);

I did this on my side and it works just fine, here's a complete example:

WEB API Controller:

public class JobController : ApiController
{
    public HttpResponseMessage Put(int id)
    {
        HttpResponseMessage response = null;
        return response;
    }
}

View:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js' type="text/javascript"></script>
<script type="text/javascript">
    angular.module('app', []);

    angular.module("app").controller('mainController', function ($scope, $http, $compile) {

        $scope.CallPut = function () {

            debugger

            var id = 1;

            $http.put("/api/Job/" + id).
            success(function (data, status, headers, config) {
                debugger;
            }).
            error(function (data, status, headers, config) {
                debugger;

            });
        }
    });

</script>

<div ng-app="app">
    <div id="mainController" ng-controller="mainController">
        <input type="button" ng-click="CallPut()" value="Call Put" />
    </div>
</div>

Also make sure you have a file called WebApiConfig.cs in the App_Start folder of your project where you define web api routes and makes sure you reister your web api routes BEFORE the MVC routes in the Global.asax file:

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

Upvotes: 3

Related Questions