Web API not populating parameter object After researching a number of articles (most specifically: Complex type is getting null in a ApiController parameter but others as well) I have arrived at the following code to pass an object parameter from an AngularJS $Resource factory to ASP.NET Web API (C#) controller. (ultimately the search object will be more complex, but I have reduced the number of properties for simplicity)
The Model:
public class SearchModel
{
public long ClientId { get; set; }
public string EmployeeName { get; set; }
public string FromDate { get; set; }
public string ToDate { get; set; }
}
The AngularJS Factory
(function () {
'use strict';
angular
.module('mainApp')
.factory('searchService', searchService);
searchService.$inject = ['$resource', 'baseApiUrl'];
function searchService($resource, baseApiUrl) {
return $resource(baseApiUrl + "api/Search", null, {
query: { method: "Get", url: baseApiUrl + "api/Search/Get:searchModel", params: { searchModel: '@searchModel' }, isArray: true }
});
})
();
When executed this code results in this URI:
https://localhost:44300/api/Search/Get?clientId=4&fromDate=3%2F1%2F2016&EmployeeName=Bob&toDate=3%2F30%2F2016
The request IS routed to the following SearchController:
[RoutePrefix("api/Search")]
public class SearchController : BaseController
{
//this c’tor contains all the necessary code to implement ninject bindings etc.
public SearchController(…): base(…)
{…}
#if !DEBUG
[Authorize] //note: this allows me to execute from Fiddler w/o an auth token
#endif
[HttpGet]
[Route("{searchModel}")]
public IHttpActionResult Get([FromUri] SearchModel searchModel)
{
try
{
//Here is where I am breaking the execution to test the results:
// search model “Is” (not null) but all properties of object ARE null strings or 0 (the long)
var result = _searchQuery.Get(searchModel);
return this.GetResult(result);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
}
When I enter breakmode at the point noted above the immediate window tells me that the “Request” query string is complete as expected…
Why are my passed values NOT being populated in the SearchModel object of the controller.
[EDIT: after accepted answer I needed to add the angular controller to get to a working solution]
The Controller
(function () {
'use strict';
angular
.module('mainApp')
.controller('SearchController', SearchController);
SearchController.$inject = ['$filter', 'searchService'];
function SearchController($filter, searchService) {
var vm = this;
vm.searchModel = {
fromDate: "3/1/2016",
toDate: "3/30/2016",
clientId: 4,
employeeName: "Bob"
}
vm.data = searchService.query(vm.searchModel);
}})();
(note that 'next' I plan to use binding to populate these values...but that I expect to achieve easily...well except for the dates...)