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

Is there a way to retrieve the current map center coordinates using the getCenter function in @react-google-maps/api?

I am currently working with the GoogleMap component provided by @react-google-maps/api, but I am struggling to figure out how to obtain the latitude and longitude coordinates of the map's center after it has been moved. After some research, I came ac ...

Is using debounce with $scope.$apply a logical choice?

In my experience, I have come across a method that claims to decrease the number of $digest loops by incorporating debouncing into the $scope.$apply process. It looks something like this: $scope.$apply = _.debounce($scope.$apply, 250); Is this approach v ...

Exploring JSON with JavaScript

[ {"lastName":"Noyce","gender":"Male","patientID":19389,"firstName":"Scott","age":"53Y,"}, {"lastName":"noyce724","gender":"Male","patientID":24607,"firstName":"rita","age":"0Y,"} ] The data above represents a JSON object. var searchBarInput = TextInput. ...

Passing a state object in a POST request body, only to find it arriving empty at the Express server

I'm having an issue with my React form component when making a POST request. The body of the request is showing up as {} even though I'm trying to send my State object. Within my form Component, I am passing the state information to another Reac ...

Is it possible to convert a JSON array into attributes of a class through deserialization?

I am faced with a JSON file that includes entries structured like this: {"id":"0258","name":"Canterbury","coordinates":[1.07992,51.27904]} Within each entry, the coordinates field represents the geographic coordinates of the city. However, it is stored a ...

Filtering for Material Autocomplete is limited to the getOptionLabel field

Currently, I am utilizing the Google Material-UI autocomplete component. It is currently only filtering based on the "getOptionLabel" option field when text is entered into the input field. However, I would like the autocomplete to filter based on more tha ...

"Integrating JavaScript in C# Code Behind: A Step-by-Step Guide

Is there a way to trigger this javascript function using C# code in the backend when the page loads? Your assistance is greatly appreciated, thank you. <script type="text/javascript"> document.onkeydown = function (event) { event = ( ...

The functionality of the controls is not functioning properly when attempting to play a video after clicking on an image in HTML5

While working with two HTML5 videos, I encountered an issue with the play/pause functionality. Despite writing Javascript code to control this, clicking on one video's poster sometimes results in the other video playing instead. This inconsistency is ...

The error message "Next.js 14 does not recognize res.status as a function"

I'm a newcomer to Next.js and I've been wrestling with an issue all day. Here's my API for checking in MongoDB if a user exists: import {connect} from '../../../../lib/mongodb'; import User from '../../../models/userModel&ap ...

Concealing overflow for text content through CSS styling

I am currently working with an element that contains both an image and text. View the Fiddle here Note: To see the full grid, resize the preview accordingly. The CSS I have written is as follows: .gridster .gs-w .item{ position: relative; wi ...

How to Send C# Array as a Parameter to a JQuery Function

I'm currently working on passing a C# array to a JQuery function as a parameter. The C# code I have to call the function is: //Create an Array from filtered DataTable Column var GatepassIDs = defaultView.ToTable().AsEnumerable().Select(r => r ...

Angular deep nested router interface

How can I set up nested views in Angular for the following routes? /#/app/dashboard /#/app/product/ /#/app/product/new Here is my current route configuration: $stateProvider .state('app',{ url: '/app', templateUrl ...

What is the recommended method for writing JavaScript scripts with AJAX in a Rails application? How can URLs be incorporated into the script effectively?

When incorporating AJAX into my Rails application, I encounter difficulties when specifying the URL for the request within a script. While it is recommended to use helpers like my_resource_path instead of manually writing paths, these helpers do not functi ...

The error message "TypeError: dom.getElementsByTagName is not a function in Node.js" indicates

I have just started learning HTML and web development. I am trying to extract a list of tags from an HTML document but I keep receiving the error message TypeError: dom.getElementsByTagName is not a function. I am making a GET request using axios, then u ...

Alerts in online software when there is a modification in the database

I am working on a project to create a web application that needs to display notifications, like the ones you see on Facebook, whenever there is a new update in the database. I could use some assistance with implementing this feature. Are there any third- ...

What exactly does the question mark represent in the code structure as indicated in VSCode?

When looking at the image, you can see that in the description of done(), VSCode indicates the type of parameters using a colon error: any or sometimes with a question mark and colon user?: any. So, what exactly is the distinction between these two ways o ...

Array contains a copy of an object

The outcome I am striving for is: dataset: [ dataset: [ { seriesname: "", data: [ { value: "123", }, { value: &q ...

I'm looking for guidance on how to merge my JavaScript and CSS files together. Can anyone provide me

As a beginner in web development, I have been looking into combining JS and CSS files. However, explanations using terms like minifies and compilers on platforms like Github and Google are still confusing to me. Here are the CSS files I have: bootstrap ...

Ruby on Rails JSON API - flawless JSON without any errors

When I am displaying an array of ActiveRecord items, each has been processed through the valid? method so errors are already defined. The rendering of the array is done as follows: render json: array_of_objects I have ActiveModelSerializers.confi ...

Can TypeScript modules be designed to function in this way?

Seeking to create a versatile function / module / class that can be called in various ways: const myvar = MyModule('a parameter').methodA().methodB().methodC(); //and also this option should work const myvar = MyModule('a parameter') ...