Issue with AngularJs failing to display data

As a newcomer to AngularJS, I am looking to utilize AngularJs to display the Json output from my MVC controller. Here is the code snippet for my MVC Controller that generates Json:


        [HttpGet]
        public JsonResult GetAllData()
        {
            int Count = 50;
            return Json(Workflow.Teacher.GetTeachers(Count), JsonRequestBehavior.AllowGet);
        }
    

This is the Angular Controller responsible for calling the GetAllData Action method:


        angular.module('myFormApp', [])
    .controller('HomeController', function ($scope, $http, $location, $window) {
        $scope.teacherModel = {};
        $scope.message = '';
        $scope.result = "color-default";
        $scope.isViewLoading = false;
        $scope.ListTeachers = null;
        getallData();

    //******=========Get All Teachers=========******  
        function getallData() {
            $http({
                method: 'GET',
                url: '/Home/GetAllData'
            }).then(function successCallback(response) {
                $scope.ListTeachers = response;
                console.log($scope.ListTeachers);
            }, function errorCallback(response) {
                $scope.errors = [];
                $scope.message = 'Unexpected Error while saving data!!';
                console.log($scope.message);
            });
        };
    })
    .config(function ($locationProvider) {
        $locationProvider.html5Mode(true);
    });
    

Additionally, here is the layout markup for my MVC views:


        @{
            Layout = "~/Views/Shared/_Layout.cshtml";
        }

        <h2>Teachers List</h2>

        <div id="content" ng-controller="HomeController">
            <span ng-show="isViewLoading" class="viewLoading">
                <img src="~/Content/images/ng-loader.gif" /> loading...
            </span>
            <div ng-class="result">{{message}}</div>

            <table class="table table-striped">
                <tr ng-repeat="teacherModel in ListTeachers">
                    <td>{{teacherModel.TeacherNo}}</td>
                    <td>{{teacherModel.TeaFName}}</td>
                    <td>{{teacherModel.TeaSName}}</td>
                </tr>
            </table>
        </div>

        @section JavaScript{
            <script src="~/Scripts/angular.js"></script>
            <script src="~/ScriptsNg/HomeController.js"></script>
        }
    

In addition, the main layout's body tag contains the ng-app directive:

<body ng-app="myFormApp">

I am using MVC version 5 along with AngularJs v1.6.4. During debugging, the getallData() actionMethod is being called and fetching rows in Json format. However, despite no errors, the model values are not rendering as expected.

Any insights or suggestions on this issue would be greatly appreciated.

Answer №1

make sure to utilize response.data for retrieving the data efficiently.

modify

$scope.ListTeachers = response;

with this adjustment

$scope.ListTeachers = response.data;

Answer №2

There are several issues with this code that need to be addressed. Firstly, the use of

$scope.ListTeachers = null;

makes it more complex to manipulate this variable later on. If you anticipate receiving an array from a REST interface, it is better to initialize it as an empty array.

$scope.ListTeachers = [];

This is important because overwriting the object can disrupt Angular's functionality that is tied to the object.

The correct way to update the data would be like this:

then(function successCallback(response) {
        // this callback will be executed asynchronously
        // when the response is received
        $scope.ListTeachers.length = 0;

        if(response && response.data){
            response.data.forEach(function item(currentValue) 
                {
                    $scope.ListTeachers.push(currentValue);
                });
         }
        console.log($scope.ListTeachers);
    }

I trust this clarifies things for you.

Answer №3

You can access various parameters in the callback response, such as data, headers, status, and statustext, to verify your request.

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

Testing with Phantom/Casper in a browser-based environment

Currently, I am utilizing Casper for UI testing on websites. My main concern is regarding the compatibility testing in various browsers such as IE, Chrome, and Firefox using Casper. If this cannot be achieved with Casper, I am open to alternative methods ...

Encountering difficulty extracting subarray from PHP json_decoded array

After receiving a JSON response, I successfully converted it into an array using json_decode. When I use var_dump to inspect the array, I get the following output: array(1) { ["FlightInfoResult"]=> array(2) { ["next_offset"]=> in ...

transform JSON structure into an array

Is it possible to convert an interface class and JSON file into a list or array in order to work on it? For example, extracting the Racename from each object in the JSON file and storing it in a list/array. Here is the interface structure: interface IRunn ...

Learn the process of directing to a view in a jQuery AJAX call with Spring MVC

Below is the ajax call I am using: $.ajax({ type: "POST", url: contextPath +"/action", cache:false, dataType: 'text', data: {Id:Id}, success: funct ...

Utilizing Ajax technology to load script in Tapestry 5

I have two components, a "DirectoryViewer" and a "MediaViewer", that I created. The Directory Viewer displays a list of file names and contains a MediaViewer component to show the selected file. This setup is functioning properly. Within the DirectoryView ...

Tips for changing an angular variable string before sending it to a PHP function

When working with AngularJS, I can access form variables within my function like this (for example: s1 = Joe Smith). However, I have a need to update the Indata variable by replacing the a_searchvalue1 with the value stored in s1 but wrapped in quotes. O ...

Ways to specify the specific option within a select field

Here is my question: <select name="currency" id="currency"> <option value="AUD"&lgt;AUD</option> <option value="BDT"&lgt;BDT</option> <option value="EUR"&lgt;EUR</option> & ...

Issues with parsing XML data when using the xml2js library

I am looking to extract and populate values from a large XML dataset into a mySQL table. The XML data structure is as follows: <BMS version="1.0"> <Summaries> <Summary Booking_strId="CWBL00D7CB8J8U" Booking_lngId="466244159" Trans_lngId="4 ...

Adjusting the height of a GAS iframe in WordPress with iframe-resizer: A step-by-step guide

I would like to embed an iframe of my Google Application Script Web into my WordPress site without the scroll bar. Refer to the image below for context. https://i.stack.imgur.com/7L6Tw.png I encountered an error message while attempting to use the iframe ...

Is there a way to transform this nested json string into a Java object?

Help needed with converting a JSON string in a unique "special" format into a Java object. Struggling to access individual values such as the location or "resolved_at". Tried using GSON and JSONPOBJECT without success. { "result": { "upon_approval ...

What could be causing the jQuery change function to stop working after loading HTML with AJAX?

When loading a form, I use AJAX to dynamically populate a select element from a PHP file. Previously, my change function was working fine (it displayed another input when 'other' was selected). However, after implementing the dynamic AJAX populat ...

What is the best way to add data from an array to a DOM element in the same order it was retrieved from Firebase?

Utilizing Google Firebase Firestore for data storage and the Open Movie Database (OMD) in combination with Axios to retrieve movie information. I am currently developing a website that allows users to add movies to collections. On the collections page, al ...

Automatically save user input in form fields with the help of jQuery and AJAX technology

I'm working on a form that has various input fields, and I need the data entered by the user to be automatically stored in the database every minute. After the user submits the request, it will be processed in a struts file where database interactions ...

What is the best way to access the iframe element?

This is main.html <body> <iframe id="frame" src="frame.html"></iframe> <script type="text/javascript"> document.getElementById('frame').contentWindow.document.getElementById('test').innerHtml = &apos ...

What could be causing issues with my JavaScript AJAX?

I'm in the process of developing a basic chat system that automatically loads new messages as they come in. Initially, I used to fetch all messages from the database. However, I encountered an issue where the scroll bar would constantly jump to the bo ...

Conceal Tooltips with Materialize CSS

I'm trying to figure out how to hide the tooltip that appears when hovering over this element using Materialize CSS. <li><a class="btn-floating green" onclick="window.print();return false;"><i class="material-icons tooltipped" data-pos ...

Prevent the Spread of an Event for a Particular Controller

tl;dr Summary Develop a function that is able to handle a specific event on multiple elements within a hierarchy. The function should execute when the event is triggered on the first element reached during bubbling, but should not continue executing or re ...

Is there a better alternative to using nested async callbacks?

Imagine I need to execute asynchronous actions like sending an email and updating the database. Usually, I would write code like this: send_email(function(err, id){ if(err){ console.log("error"); }else{ update_database(id,function( ...

Issues with AngularJS ng-bind-html failing to display list items

I am working with a basic HTML document that looks like this... <ol> <li><strong>Test 1</strong></li> <li><strong>Test 2</strong></li> </ol> ...and I am attempting to connect it to a div ...

Unpacking a props object results in an undefined value

I've been struggling to set up a data-grid in react because I'm facing issues with accessing the data from my props. Whenever I try to access or destructure the prop, it shows up as "undefined" in my console. This problem only arises when the p ...