简体   繁体   中英

I am unable to access an asp.net mvc controller to return me a JsonResult using $resource of angular

What am I missing ? I am new to Angularjs. Trying angularjs with asp.net mvc. I am unable to access an asp.net mvc controller to return me a JsonResult using $resource of angular. However, I get success otherwise using $.getJson of javascript but not using angularjs. What am I missing ? please guide. Thank you for replying any.

Following is my Service

EbsMvcApp.factory('classListService', function ($resource, $q)
{
    var resource = $resource
                    (
                      '/Home/ClassList' 
                      , {}
                     //{ method: 'Get', q: '*' }, // Query parameters
                       , { 'query': { method: 'GET' , isArray:false  } }
                    );

    function get($q)
    {
        console.log('Service: classListServic > Started');

        var Defered = $q.defer();

        resource.get
            (
                 function (dataCb)
                 {
                     console.log('success in http service call');
                     Defered.resolve(dataCb);
                 }
                , function (dataCb)
                {
                    console.log('error in http service')
                    Defered.reject(dataCb);
                }
            );
        return Defered.promise; // if missed, would throw an error on func: then.
    };
    return { get: get };
});

angular Controller:

var EbsMvcApp = angular.module('myApp', ['ngResource']);

//'classListService',
EbsMvcApp.controller
    (
        'myAppController',
        ['$scope','classListService','$q' , function ($scope, classListService, $q)
            {
                    console.log('controller myAppController started');

                    var classList = classListService.get($q);
                   classList =  classList.then( 

                        function ()
                        {
                            (
                            function (response)
                            {
                                console.log('class list function response requested');
                                return response.data;
                            }
                        );
                       }
                    );

                   console.log(classList.ClassName);
                   console.log(classList);

                    console.log('end part of ctrl');
                    $scope.classList = classList;
                    $scope.SelectedClassID = 0;
                    $scope.message = ' message from Controller ';

            }
        ]
    );

Asp.net MVC Controller

namespace EBS_MVC.Controllers
    {
        public class HomeController : BaseController
        {
            ApplicationDbContext db = new ApplicationDbContext();

                public JsonResult ClassList()
            {
                var List = new SelectList(db.tblClass, "ID", "ClassName");

                return Json(List, JsonRequestBehavior.AllowGet);
            }
       }
    } 

Brower's response (F12):

ControllerTry1.js:11 controller myAppController started serviceGetClassList.js:16 Service: classListServic > Started ControllerTry1.js:28 undefined ControllerTry1.js:29 c ControllerTry1.js:31 end part of ctrl angular.js:12520 Error: [$resource:badcfg] [Browers response: screen shot][1]

Oky, finally, I got a solution using the $http service. from here

http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/05/13/how-to-use-angularjs-in-asp-net-mvc-and-entity-framework-4.aspx

in csHtml file, a reference to the service.js and Controler.js is required. I am not sure if I have added it earlier or later now. but its required.

ng-Controller:

    EbsMvcApp.controller('ClassListController', function ($scope, ClassListService2) {    

            console.log('ClassListController Started');

            GetClassList();

            function GetClassList()
            {
                ClassListService2.GetJson()
                        .success(function (dataCallBack) {
                            $scope.classList = dataCallBack;
                            console.log($scope.classList);
                        })
                        .error(function (error) {
                            $scope.status = 'Unable to load data: ' + error.message;
                            console.log($scope.status);
                        });
            }
        });

ng-Service:

    EbsMvcApp.factory('ClassListService2', ['$http', function ($http) {


    console.log('ClassListService2 Started');

    var list = {};
    list.GetJson = function () {
        return $http.get('/Home/ClassList');
    };
    return list;

}]);

csHtml View:

    <div class="text-info" ng-controller="ClassListController">
<h3> Text from Controller: </h3>

@*table*@
<table class="table table-striped table-bordered">
    <thead>
        <tr><th>DisplayName</th><th>Value</th>
    </thead>
    <tbody>
        <tr ng-hide="classList.length">
            <td colspan="3" class="text-center">No Data</td>
        </tr>
        <tr ng-repeat="item in classList">
            <td>{{item.Text}}</td>
            <td>{{item.Value}}</td>

        </tr>
    </tbody>
</table>

Sorry for the delay, I just wrote up some code to quickly test the ngResource module as I haven't used it yet.

I've got the code working to do what you want using the ngResource module. I think part of the problem was that you was configuring the query method but calling the get method so your configurations was not applied.

Here is the service class that I wrote to test against a controller the same as yours.

(function () {
    'use strict';

    angular
        .module('myApp')
        .service('classService', ClassService);

    ClassService.$inject = ['$resource', '$q'];

    function ClassService($resource, $q) {

        var resource = $resource
        (
            '/Home/ClassList',
            {},
            {
                'get': { method: 'GET', isArray: true },
                'query': { method: 'GET', isArray: true }
            }
        );

        var service = {
            get: get
        };

        return service;

        ////////////

        function get() {
            var Defered = $q.defer();

            resource.get(function (dataCb) {
                console.log('success in http service call');
                Defered.resolve(dataCb);
            }, function (dataCb) {
                console.log('error in http service')
                Defered.reject(dataCb);
            });

            return Defered.promise;
        };
    };
})();

The controller looks like this

(function () {
    'use strict';

    angular
        .module('myApp')
        .controller('classController', ClassController);

    ClassController.$inject = ['$scope', 'classService'];

    function ClassController($scope, classService) {

        var vm = this;
        vm.data = null;

        activate();

        /////////////

        function activate() {

            var classList = classService.get().then(function (response) {
                console.log('class list function response requested');
                vm.data = response;
                console.log(vm.data);
            });

            console.log('end part of ctrl');
            $scope.SelectedClassID = 0;
            $scope.message = ' message from Controller ';
        };

    };
})();

I've included some of your original code just so you can see how it would fit in.

Glad to see you have got it working though!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM