angularjs - controller actions not working

前端 未结 1 764
梦谈多话
梦谈多话 2021-01-29 05:31

sorry if im doing something wrong im new here \'^^

im curently working on a school project building a website using MVC. im trying to load objects from a database using

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-29 06:12

    I think you are getting a 404 error when your angular code is trying to make the asynchronous call to your action method because the relative path you gave to the action method is not correct.

    It is not a good idea to hardcore your url in your javascript like this. Yo should use the Url.Content() or Url.RouteUrl() helper methods in your razor view to generate the relative url to the app root. It will take care of correctly building the url regardless of your current page/path.Once you get this value, you can pass it to your angular controller using the angular value provider.

    So in your razor view (Layout file or your specific view), you may do this.

    
    
    
    

    And in your angular controllers(in the external AngularControllerForPage.js file), you can access it like,

    var app = angular.module("myProduct", []);
    var ctrl = function (appSettings,$http) {
    
        var vm = this;
    
        vm.products = [];
    
        vm.baseUrl = appSettings.Urls.baseUrl;
    
        //build other urls using the base url now
        var loadProductsUrl = vm.baseUrl + "YourControllerNameHere/GetProductsByJson";
        console.log(loadProductsUrl);
    
        // now you can use loadProductsUrl to make the $http call
    
        $http.get(loadProductsUrl).then(function(response) {
               vm.products=response.data;
             }
    
    };
    ctrl.inject=['$http'];
    app.controller("ProductViewModel", ctrl);
    

    You can see that i am accessing the response in the then() event of $http service. Also the above controller code is written in such a way to to support the controller As syntax as suggested by john papa in his angular styleguide. So in your view ,you will access it like

    {{vm.products.length}} Items

    0 讨论(0)
提交回复
热议问题