سؤال

I am trying to write web application with ASP.net webAPI and knockout and using IIS. Here I am trying to initiate view model on Admin page (http://localhost/Attendance/Home/Admin). The API to fetch all users is at path http://localhost/Attendance/user. This url returns the users when accessed from browser.

However when I access it from below javascript

    function adminuservm() {
    //Properties
    self = this;
    self.users = ko.observableArray();
    self.user = ko.observable();
    self.userscount = ko.computed(function () {
        if (self.users == null)
            return 0;
        else
            return self.users.length;    
    }, this);
    //Methods
    //Get all users
    self.getAllUsers = function () {
        $.getJSON("api/user", function (data) {
        })
        .done(function (data) { //success
            if(data != null)
            self.users = $.map(data, function (u) { return new user(u) });
        })
        .fail(function (data) { //error
            alert("error");
        });
    };

    //call getAllUsers to populate all users
    self.getAllUsers();
}

The getjson method does not form correct url when I give realtive path to web api resource thus I get 404 error. The URL it calls is http://localhost/Attendance/Home/api/user. Then I tried putting that code on http://localhost/Attendance/Home/Index view and it worked there.

I do not want to use hardcoded URL in javascript. is there any way out?

Thank you in advance.

هل كانت مفيدة؟

المحلول

You need to change the URI to /Attendance/api/user like below:

self.getAllUsers = function () {
    $.getJSON("/Attendance/api/user")
       .done(function (data) { //success
                if (data != null)
                self.users = $.map(data, function (u) { return new user()});
            })
       .fail(function (data) { //error
                alert("error");
            });
};

Also make sure you have a route like below in your WebApiConfig class.

    config.Routes.MapHttpRoute(
        name: "",
        routeTemplate: "Attendance/api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top