-1

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 Json object and angularJS.

i have an action in a contoller called "GetProductsByJson" it returns a Json object containing a list of products. this is the action:

public ActionResult GetProductsByJson()
        {
            HomeModel homeModel = new HomeModel();
            DataLayer prodDal = new DataLayer();
            homeModel.productList = prodDal.Products.ToList<Product>();
            return Json(homeModel.productList,JsonRequestBehavior.AllowGet);
        }

the action it self works good (i tested it individualy) but when im trying to use it in the angular script its just not working (it doesnt even go into the method).

this is the angular script:

<script>
        var app = angular.module("myProduct", []);
        app.controller("ProductViewModel", function ($scope,$http) {

            $scope.Product = {
                "prodName": "",
                "price": "",
                "amount": "",
                "serial": "",
                "lastUpdate": "",
                "pic": ""
            };

            $scope.Products = {};

            $scope.LoadProducts = function () { //load data from the server
                debugger
                $http({ method: "GET", url: "LoadProducts" }).
                success(function (data, status, headers, config) {
                    $scope.Products = data;
                });
            };

            $scope.LoadProducts();
        });
 </script>

i tried routing the action in the RouteConfig but nothing works.

ok im really sorry for the trouble problem solved.

i had to insert the full url of the action apperntly.

Ron Bitterman
  • 131
  • 1
  • 6
  • Load the developer toolbar in your browser and see if a request is being made to the server (in the Network tab). If so, what does the server return? When you write `url: "LoadProducts"` this will make a request to `/LoadProducts`. Are you sure that your MVC application will correctly respond to such route? – Darin Dimitrov Jan 03 '16 at 21:06
  • Have your angular bootstrapped at all? – Hamlet Hakobyan Jan 03 '16 at 21:07
  • far too many unknowns and horrible problem description. Use debugging tools in browser console to investigate further – charlietfl Jan 03 '16 at 21:09
  • show html where you invoke the method. Also, when you say "I have a method LoadProducts", it is confusing. Both your Angular and Server methods are called LoadProducts. So, when you say "it doesn't go to that method" - to which method it doesn't go? – Felix Jan 03 '16 at 21:09

1 Answers1

0

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.

<script>
    var myApp = myApp || {};
    myApp.Urls = myApp.Urls || {};
    myApp.Urls.baseUrl = '@Url.Content("~")';       
</script>
<script src="~/Scripts/AngularControllerForPage.js"></script>
<script>
    var a = angular.module("myProduct").value("appSettings", myApp);
</script>

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

<div ng-app="myProduct" ng-controller="ProductViewModel as vm">
    <h1>{{vm.products.length}} Items</h1>    
</div>
Shyju
  • 214,206
  • 104
  • 411
  • 497