Reputation: 2622
I have the following Api Controller:
public class FamilyController : ApiController
{
ApplicationDb db = new ApplicationDb();
public IEnumerable<Family> GetFamilies()
{
return db.Families.AsNoTracking().OrderBy(n => n.FamilyName);
}
public Family GetFamily(int id)
{
return db.Families.AsNoTracking().Single(n => n.FamilyID == id);
}
}
The following javascript file called functions.js
(function () {
window.dbApp = window.dbApp || {};
// Private: Routes
var familiesUrl = function () { return "/api/family/getfamilies" },
familyUrl = function (id) { return "/api/family/getfamily?id=" + id };
// Private: Ajax helper
function ajaxRequest(type, url, data) {
var options = { dataType: "json", contentType: "application/json", cache: false, type: type, data: ko.toJSON(data) }
return $.ajax(url, options);
}
// Public: Methods
window.dbApp.Db = {
getFamilies: function() {
return ajaxRequest("get",familiesUrl());
},
getFamily: function (id) {
return ajaxRequest("get", familyUrl(id));
},
};
})();
And the following javascript on a view:
@Scripts.Render("~/bundles/knockout")
@Scripts.Render("~/bundles/functions")
<script type="text/javascript">
function viewModel() {
var self = this;
self.Families = ko.observableArray([]);
self.Init = function () {
dbApp.Db.getFamilies()
.done(function (data) {
self.Families(data);
});
};
self.Init();
}
var model = new viewModel();
ko.applyBindings(model);
</script>
But I get the following error returned: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'MadcapsPortal.Models.Family GetFamily(Int32)' in 'MadcapsPortal.Controllers.FamilyController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
It's like it's calling the wrong function. What's strange is that another page that uses the following works fine??
var passedId = @ViewBag.PassedID;
function viewModel() {
var self = this;
self.Family = ko.observable();
self.FamilyName = ko.observable();
self.Init = function() {
dbApp.Db.getFamily(passedId)
.done(function(data){
self.Family(data);
self.FamilyName(data.FamilyName);
});
};
self.Init();
}
var model = new viewModel();
ko.applyBindings(model);
Upvotes: 1
Views: 427
Reputation: 3280
You are supposed to use the follwing URL's:
GET /api/family
GET /api/family/2
or GET /api/family?id=2
Please read this for more information on ASP.NET Web API routing:
But basically: The URL to action method mapping will mainly be determined my the HTTP method and patterns in your action method names and the methods' signatures. GET /api/family
will be mapped to a method named somewhat like get and containing no further parameters.
Upvotes: 1