Search code examples
c#javascriptasp.net-mvc-4knockout.jsasp.net-web-api

getJSON doesnt call webAPI method


Im new on mvc 4 and webAPI and Im developing my first application on it.It is single page application and using Knockoutjs.I use this walkthrough https://github.com/geersch/KnockoutSpa/
every thing is fine with my webAPI method and it return correct value when I call method with Fiddler.But it never called when I use it from getJson() method.Here is my HTML:

    <table id="nqsales" class="table table-striped table-hover table-condensed">
    <thead>
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: viewModel.nqsales">
        <tr>
            <td data-bind="text: a"></td>
            <td data-bind="text: b"></td>
            <td data-bind="text: c"></td> 
        </tr>
    </tbody>
    </table>

Javascript

$(function () {
    ko.applyBindings(viewModel);
    viewModel.loadNqsales();
});

var viewModel = {
    nqsales: ko.observableArray([]),

    loadNqsales: function () {
        var self = this;
        $.getJSON(
            '@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "NQSale" })',
    function (nqsales) {
        self.nqsales.removeAll();
        $.each(nqsales, function (index, item) {
            self.nqsales.push(new nqsale(item));
        });
    }
);
    }
};

function nqsale(nqsale) {
    this.expenceFormNo = ko.observable(nqsale.a);
    this.orderNo = ko.observable(nqsale.b);
    this.date = ko.observable(nqsale.c);
}

WebAPIController

    // GET api/NQSale
    public IEnumerable<NQSaleDto> GetNQSales()
    {
        //return db.NQSales.AsEnumerable();
        return db.NQSales
            .AsEnumerable()
            .Select(nqlist => new NQSaleDto(nqlist));
        
    }

Solution

  • Your Url construction of

    @Url.RouteUrl("DefaultApi", new { httproute = "", controller = "NQSale" })

    should generate a URL of '/api/NQSale' this means that your controller should be the following:

    //The controller name relates to the route
        public class NQSaleController : ApiController
    {
    // The action name relates to the HttpVerb
        public IEnumerable<NQSaleDto> Get()
        {
            //return db.NQSales.AsEnumerable();
            return db.NQSales
                .AsEnumerable()
                .Select(nqlist => new NQSaleDto(nqlist));
    
        }
    }
    

    By default, the routing for API is that the name of the controller (NQSaleController) relates to the path and the name of the Action (Get) relates to the HttpVerb.