Francesco Galeota Francesco Galeota - 8 days ago 5
AngularJS Question

AngularJS pass Parameter to Web Api Get

i'm trying to pass object parameter from angularJs controller to Web Api 2 Get Method controller.

If i pass object like string it will work but i don't like this solution.

[HttpGet]
public IEnumerable<SearchVenueByParameters_Result> Get(string parameter)
{
ObjSearch obj_search = new JavaScriptSerializer().Deserialize<ObjSearch>(parameter);


I would like to try this one :

[HttpGet]
public IEnumerable<SearchVenueByParameters_Result> Get(ObjSearch obj_search)


ObjSearch class :

public class ObjSearch {
public string aAMSID { get; set; }
public string venueName { get; set; }
public string address { get; set; }
public byte? businessSK { get; set; }
public string subjectAamsCode { get; set; }
public string subjectDenomination { get; set; }
public string subjectVatNumber { get; set; }
public string subjectTaxCode { get; set; } }


And in angularjs controller i have :

$scope.objSearch = {
"aAMSID": "",
"venueName": "",
"address": "",
"businessSK": "",
"subjectAamsCode": "",
"subjectDenomination": "",
"subjectVatNumber": "",
"subjectTaxCode": ""
}

$scope.searchVenueByParameters = function () {

var strObjSearch = angular.toJson($scope.objSearch);
console.log(strObjSearch);
$http({
url: '/api/SearchVenueByParameters_Result/',
method: 'GET',
params: { obj_search: strObjSearch }
}).success(function (data) {
$scope.Venues = data;
$scope.VenueList = true;
$scope.showItem = true;

})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
});
}


But in this case i have corrected value printed in console from angularjs controller , but the object passed in the web abi controller is always null.

Answer

When sending complex objects with GET use the [FromUri] attribute which creates your object directly from the URL.

In the client, add the object to the params

$http({
    url: '/api/SearchVenueByParameters_Result/',
    method: 'GET',
    params: $scope.objSearch
}).success(function (data) {
    $scope.Venues = data;
    $scope.VenueList = true;
    $scope.showItem = true;

The URL will be translated to something like

/api/SearchVenueByParameters_Result/?aAMSID=1&venueName=1&address=1&businessSK=1&subjectAamsCode=1&subjectDenomination=1&subjectVatNumber=1&subjectTaxCode=1

And in the controller, add the [FromUri] attribute

[HttpGet]
public IEnumerable<SearchVenueByParameters_Result> Get([FromUri]ObjSearch obj_search)

You can read more about the attribute here