I'm learning how to use AngularJS's $resource to call a Web Api backend. I want to pass an object hierarchy in as criteria and get back an IEnumerable<Program>
. Here's an example of the criteria:
$scope.criteria = {
Categories:[
{
Name: "Cat1",
Options: [
{Text: "Opt1", Value: true},
{Text: "Opt2", Value: false}
]
},
{
Name: "Cat2",
Options: [
{Text: "Opt3", Value: true},
{Text: "Opt4", Value: false}
]
}
]
}
I have the same objects defined on the server in C#.
public class CriteriaModel
{
public IEnumerable<CriteriaCategory> Categories { get; set; }
}
public class CriteriaCategory
{
public string Name { get; set; }
public IEnumerable<CriteriaOption> Options { get; set; }
}
public class CriteriaOption
{
public string Text { get; set; }
public bool Value { get; set; }
}
Here's how I am configuring $resource:
angular.module('my.services')
.factory('api', [
'$resource',
function ($resource) {
return {
Profile: $resource('/api/profile/:id', { id: '@id' }),
Settings: $resource('/api/settings/:id', { id: '@id' }),
Program: $resource('/api/program/:id', { id: '@id' })
};
}
]);
And I call it like this:
api.Program.query({ criteria: $scope.criteria }, function (response) {
$scope.programs = response;
});
No matter what I try I either get null
as the criteria parameter or the action doesn't execute at all. I don't know if the problem is in angular, web api, or both. Here is the action:
public class ProgramController : ApiController
{
public IEnumerable<Program> GetByCriteria([FromUri]CriteriaModel criteria)
{
// Either criteria is null or this action doesn't even get
// executed depending on what I try.
}
}
Can someone help me get a working example going for searching and returning items using AngularJS $resource and Web Api?