I am having trouble retrieving a JsonResult from an asp.net mvc controller using $resource in angular

I am new to Angularjs and trying to integrate it with asp.net mvc. I am facing an issue where I am unable to access an asp.net mvc controller to return a JsonResult using $resource in angular. Strangely, when I use $.getJson in JavaScript directly, it works fine but not when using angularjs. Can someone please guide me on what I might be missing? Any help would be greatly appreciated.

Below is the code snippet for 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]

Answer №1

After some persistence, I was able to find a solution by utilizing the $http service. You can refer to it here.

In the csHtml file, make sure to include references to service.js and Controller.js. Whether these were added at the beginning or later on is uncertain, but they are essential for the functionality.

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>

Answer №2

Apologies for the delay, I took some time to write up code and test out the ngResource module which is new to me.

I managed to get the code functioning as per your requirements using the ngResource module. It seems there was a confusion in configuring the query method while calling the get method, causing the configurations not to be applied correctly.

Below is the service class I created to test against a controller similar to 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 implementation is as follows:

(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 retained some of your original code for reference purposes.

Congratulations on getting everything up and running smoothly!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason behind bower installing packages twice?

Whenever I use Yeoman to install packages, which is powered by Bower in the background, I notice that each package gets duplicated... The first copy is placed in the project root under the components folder. The second copy goes inside the app/components ...

HighCharts.js - Customizing Label Colors Dynamically

Can the label color change along with gauge color changes? You can view my js fiddle here to see the current setup and the desired requirement: http://jsfiddle.net/e76o9otk/735/ dataLabels: { format: '<div style="margin-top: -15.5px; ...

Error: Failed to parse the given color specification

My chrome extension is showing an error message: Unchecked runtime.lastError: The color specification could not be parsed. This error seems to be in the popup.html: 1 -> <! DOCTYPE html> line. Can anyone explain what this means and how to fix ...

JSON sending error occurs if the data exceeds the maximum length limit when communicating with the Web

I'm encountering an issue while trying to send a JSON object to a .NET Web API. I have a multidimensional array that I convert into JSON and then send to the web service. The total length of the object exceeds 50,000 characters. However, if I slice th ...

Using checkboxes in an Express application

Currently, I am working on the task of parsing checkbox values into an array using express/ejs. Users are required to fill out a form and select checkboxes as shown below: Answer: Checkbox: The goal is to create two arrays from the input data: answer = ...

Is there a way to create Angular components sourced from an external library using JavaScript?

I'm currently developing an Angular project and leveraging an external component library called NGPrime. This library provides me with a variety of pre-built components, including <p-button> (which I am using in place of a standard <button> ...

Error compiling: Cannot locate module '../../common/form' within 'src/components/time'

An attempt to import the file form.jsx into the file time.jsx resulted in an error: Error message: Module not found: Can't resolve '../../common/form' in 'src/components/time' //src //common //form.jsx //compon ...

What are some techniques for animating SVG images?

Looking to bring some life to an SVG using the jQuery "animate" function. The plan is to incorporate rotation or scaling effects. My initial attempt with this simple code hasn't yielded the desired results: $("#svg").animate({ transform: "sc ...

The Ajax file upload handler consistently registers as zero on every request

I have encountered an issue while trying to upload files via ajax using a handler (.ashx) in webforms. The problem arises when attempting to retrieve the file data within the handler. Here is the JavaScript code I am using: $('#myImageButton') ...

Dealing with multiple Datepicker components in React hooks

Managing a single instance of Datepicker in a React project is easy, but what about handling multiple instances? The date changes are not reflected on the UI even though they can be seen in the console. What are some efficient solutions to tackle this issu ...

Angular-schema-form utilizes computed values to dynamically generate form fields based on

I am facing an issue with a form where users input values and I want to display dynamic calculations based on those values. The problem is that the calculation does not update when the numbers are changed. Here is my code snippet: angular.module('cal ...

Interacting with PHP through JavaScript function calls

I am facing some frustration with my website due to an issue involving PHP. When I retrieve data from a PHP file, it returns a JSON list like this: {"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurst ...

Tips for arranging elements in proper order following a rotation

Having trouble aligning rotated divs? Let's say we rotate .straight by 30deg, and now we want to find the new offset coordinates of its bottom right corner. This way, we can perfectly match up the bottom left corners of .curve with this new coordinate ...

Unable to retrieve any response data in Angular 2

I'm having trouble retrieving the response from my API. Despite being able to do so with PostMan, my variable "this.data" remains null. I've experimented with various approaches to no avail. Any assistance would be greatly appreciated. The method ...

Looking for giphy link within a v-for loop (Vue.js)

I am fetching a list of movie characters from my backend using axios and rendering them in Bootstrap cards. My objective is to search for the character's name on Giphy and use the obtained URL as the image source for each card. However, when I attemp ...

Adding a three-dimensional perspective to an HTML5 canvas without utilizing CSS3 or WebGL

Here is a canvas I am working with: http://jsbin.com/soserubafe Here is the JavaScript code associated with it: var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var w = canvas.width; var h = canvas.height; var cw=canvas. ...

Utilizing ng-options value in ng-change

Having a bit of trouble with my ng-options select tag. It seems like the ng-change function isn't working as expected, with the first parameter "v" coming up undefined. Anyone have any ideas on how to resolve this? <select ng-model="d.sub_customer ...

Exploring the Concept of Template Element Recursion in Angular JS 2

In my Angular 2 project, I encountered a situation where I needed to iterate through ngFor based on child elements. My component should be able to render a list based on the input provided. Here is an example of the data structure: [ { name: 'ABC ...

When iterating through a JavaScript object, opt for utilizing references instead of repeatedly specifying the path

for (var element in array[index1][index2][index3].property) { alert(array[index1][index2][index3].property[element].data); } Is there a more succinct way to achieve the same result by referencing the object directly like this: for (var ...

Transform JSON String into Object using jQuery

Recently, I came across a JSON String in this format. {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"} I needed to convert it into an object structure like this [{"label":"label","label1":"67041","label2":"745"," ...