locked
WebAPI Controller Parameter Object values are Null - $http.get() RRS feed

  • Question

  • User1628746328 posted

    I am implementing an $http.get() in AngularJS that passes an object to a Web API Controller/Action.

    AngularJS Controller Code:

      $http.get('api/Employee/GetVacancyStatus?emp='+thisData[0])
                                .then(function (response, success) {
                                    if (response.data == false){
                                        alert("cube/office occupied");
                                    }
                                    else // continue with employee move
                                    {
                                        do some stuff...
                                    }
    
                            }, function (response, error) {
                                alert(response);
                            });
                            

    When we leave the AngularJS controller, the object is populated as shown below at: $http.get('api/Employee/GetVacancyStatus?emp='+thisData[0])

    Web Api Controller Code:

        [System.Web.Http.HttpGet, System.Web.Http.ActionName("GetVacancyStatus")]
            public bool GetVacancyStatus([FromUri] employee emp)
            {
                    
                //return repository.GetVacStatus(moveQuery);
                return false;
            }

    When the execution hits my Web Api controller however, it seems that it's the object is an uninitialized.

    Not sure what I am doing incorrectly since I am new to Web API.

    Thanks.

    Thursday, March 2, 2017 4:56 PM

Answers

  • User-2057865890 posted

    Hi DrDexter33,

    You can serialize objects into strings and send them in the query string using an HTTP GET. However, depending on what you are doing, it might be better to send it using an HTTP POST.

    Working Sample

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    
        <script type="text/javascript">
            var app = angular.module("MyApp", [])
            app.controller("employeeController", function ($scope, $http) {
                var data = { "Id": 86, "seat": "41", "lName": "User", "seatTypeId": 1 };
    
                var thisData = [];
                thisData.push(data);
                $http.post(
                    '/api/employee/employee',
                    thisData[0],
                    {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }
                ).success(function (data) {
                    $scope.employee = data;
                });
            });
        </script>
    
    </head>
    <body>
        <div ng-app="MyApp" ng-controller="employeeController">
            <ul ng-model="employee">
                <li>Id: {{employee.Id}}</li>
                <li>seat: {{employee.seat}}</li>
                <li>lName: {{employee.lName}}</li>
                <li>seatTypeId: {{employee.seatTypeId}}</li>
            </ul>
        </div>
    </body>
    </html>
    

    Controller

     public class EmployeeController : ApiController
     {
         [System.Web.Http.HttpPost, System.Web.Http.ActionName("GetVacancyStatus")]
         public employee GetVacancyStatus(employee emp)
         {
             return emp;
         }
     }

    Model

     public class employee
     {
         public int Id { get; set; }
         public string seat { get; set; }
         public string lName { get; set; }
         public int seatTypeId { get; set; }
     }

    Best Regards,

    Chris

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 3, 2017 5:39 AM
  • User527778624 posted

    Hi,

    Try like this:

    var serialize = function (obj) {
    	var str = [];
    	alert("ser");
    	for(var p in obj){
    		if (obj.hasOwnProperty(p)) {
    			str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    		}
    	}
    	return str.join("&");
    }
    
    $http.get('api/Employee/GetVacancyStatus?' + serialize(thisData[0]))

    or, try Jquery:

    var result = $.param(thisData[0]);
    $http.get('api/Employee/GetVacancyStatus?' + result)

    Issue with your attempted code is ?emp= where emp= is not required.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 3, 2017 6:47 AM

All replies

  • User527778624 posted

    Hi,

    In Javascript, You can't concat string to an Object type.

    write logic such that object is converted to query string, then concat.

    http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object

    or you can use jquery function param: $.param(thisData[0])

    http://api.jquery.com/jquery.param/

    Thursday, March 2, 2017 5:38 PM
  • User1628746328 posted

    Tried the SO link:

      var obj = thisData[0];
    
                            serialize = function (obj) {
                                var str = [];
                                alert("ser");
                                for(var p in obj){
                                    if (obj.hasOwnProperty(p)) {
                                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                                    }
                                }
                                return str.join("&");
                            }

    The function never gets executed and is bypassed completely.

    Also tried JQuery:

    var result = $.param(thisData[0]);
    $http.get('api/Employee/GetVacancyStatus?emp=' + result)

    The object in the Web API controller is still uninitialized.

    Thursday, March 2, 2017 7:18 PM
  • User-2057865890 posted

    Hi DrDexter33,

    You can serialize objects into strings and send them in the query string using an HTTP GET. However, depending on what you are doing, it might be better to send it using an HTTP POST.

    Working Sample

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    
        <script type="text/javascript">
            var app = angular.module("MyApp", [])
            app.controller("employeeController", function ($scope, $http) {
                var data = { "Id": 86, "seat": "41", "lName": "User", "seatTypeId": 1 };
    
                var thisData = [];
                thisData.push(data);
                $http.post(
                    '/api/employee/employee',
                    thisData[0],
                    {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }
                ).success(function (data) {
                    $scope.employee = data;
                });
            });
        </script>
    
    </head>
    <body>
        <div ng-app="MyApp" ng-controller="employeeController">
            <ul ng-model="employee">
                <li>Id: {{employee.Id}}</li>
                <li>seat: {{employee.seat}}</li>
                <li>lName: {{employee.lName}}</li>
                <li>seatTypeId: {{employee.seatTypeId}}</li>
            </ul>
        </div>
    </body>
    </html>
    

    Controller

     public class EmployeeController : ApiController
     {
         [System.Web.Http.HttpPost, System.Web.Http.ActionName("GetVacancyStatus")]
         public employee GetVacancyStatus(employee emp)
         {
             return emp;
         }
     }

    Model

     public class employee
     {
         public int Id { get; set; }
         public string seat { get; set; }
         public string lName { get; set; }
         public int seatTypeId { get; set; }
     }

    Best Regards,

    Chris

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 3, 2017 5:39 AM
  • User527778624 posted

    Hi,

    Try like this:

    var serialize = function (obj) {
    	var str = [];
    	alert("ser");
    	for(var p in obj){
    		if (obj.hasOwnProperty(p)) {
    			str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    		}
    	}
    	return str.join("&");
    }
    
    $http.get('api/Employee/GetVacancyStatus?' + serialize(thisData[0]))

    or, try Jquery:

    var result = $.param(thisData[0]);
    $http.get('api/Employee/GetVacancyStatus?' + result)

    Issue with your attempted code is ?emp= where emp= is not required.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 3, 2017 6:47 AM
  • User1628746328 posted

    Thanks for the help.!

    Have a good weekend

    Friday, March 3, 2017 10:09 PM