Search code examples
c#javascriptasp.net-mvc-4knockout.jsodata

Odata Routing and accessing it using Knock out Js


I have worked on an application on Asp.Net Mvc4 Internet Application with OData and Knockout Js. Routing in my OData is as follows

WebApiConfig.cs

ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder();
            modelBuilder.EntitySet<Product>("Products");
            var model = modelBuilder.GetEdmModel();

            config.Routes.MapODataRoute(routeName: "Odata", routePrefix: "odata", model: model);

And Knockout Js as follows

 $.getJSON('odata/Products', function (data) {
        self.products(ko.utils.arrayMap(data.value, function (product) {
            var obsProduct = {
                Id: product.Id,
                ProductName: ko.observable(product.ProductName),

                Edit: ko.observable(false),
                Locked: ko.observable(product.Locked)
            }
            self.watchModel(obsProduct, self.modelChanged);
            return obsProduct;
        }));
        self.loading(false);
    });
}

But while running an application, it threw an exception as follows

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:57044/Home/odata/Products

But when I manually enter the URL http://localhost:57044/odata/Products , is is showing the meta data which has all the list of products

But when I enter http://localhost:57044/Home/odata/Products(this is a different url from the above), it is throwing a 404 error. How do I fix it


Solution

  • /Home/odata/Products

    --> this is the problem, the HOME, your url is incorrect

    $.getJSON('/odata/Products', function (data) {
        self.products(ko.utils.arrayMap(data.value, function (product) {
            var obsProduct = {
                Id: product.Id,
                ProductName: ko.observable(product.ProductName),
    
                Edit: ko.observable(false),
                Locked: ko.observable(product.Locked)
            }
            self.watchModel(obsProduct, self.modelChanged);
            return obsProduct;
        }));
        self.loading(false);
    });