Instead of returning a JSON result, the MVC controller method called from AngularJS is returning the view HTML

Within the HomeController, I have the following method,

[HttpGet]
        public ActionResult GetStudents()
        {
            Student std1 = new Student();
            List<Student> stdlst = new List<Student>();
            std1.Id = 1;
            std1.Name = "Emmanuvel";
            std1.Age = 25;
            stdlst.Add(std1);

            Student std2 = new Student();
            std2.Id = 2;
            std2.Name = "Michael";
            std2.Age = 24;
            stdlst.Add(std2);

            Student std3 = new Student();
            std3.Id = 3;
            std3.Name = "Hannah";
            std3.Age = 22;
            stdlst.Add(std3);

            return Json(stdlst, JsonRequestBehavior.AllowGet);
        }

I am trying to access this method through an AngularJS Ajax call as shown below,

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
    $scope.ButtonClick = function () {            
        $http.get('@Url.Action("GetStudents","Home")')
            .success(function (data) {
                $scope.students = data;
                console.log($scope.students);                    
            })
            .error(function (data) {
                console.log(data);
            });
    }
});
</script>

However, when logging the data using console.log, it is displaying HTML code of the view page instead of JSON data. The output in the console is as follows:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>


    <div ng-app="MyApp" ng-controller="MyController">
        <input type="button" value="Submit" ng-click="ButtonClick()"/>
    </div>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
    var app = angular.module('MyApp', [])
    app.controller('MyController', function ($scope, $http, $window) {
        $scope.ButtonClick = function () {            
            $http.get('/Home/GetStudents')
                .success(function (data) {
                    $scope.students = data;
                    console.log($scope.students);                    
                })
                .error(function (data) {
                    console.log(data);
                });
        }
    });
    </script>
</body>
</html>

I need assistance in identifying the error present in this code snippet.

Answer №1

I have a few suggestions for improving the code in question. To start, I recommend separating the angular code from the view. While it may seem convenient to use Razor syntax for building URLs, this creates a dependency that can complicate things.

Here's what I propose:

  1. Move the angular controller to its own file.
  2. Update the JavaScript URL to '/Home/GetStudents'.
  3. Change the return type of the backend controller to JsonResult instead of ActionResult. Even if you're returning JSON data, using ActionResult can still result in the page returning HTML content.

After making these changes, make sure to test in the browser by directly calling the '/Home/GetStudents' URL to ensure proper data retrieval. Then, set breakpoints to verify that Angular is correctly receiving the data before moving forward.

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

Utilizing for loop and specific string selectors in an undefined AJAX post request

Greetings fellow developers! I have been exploring jquery/ajax and here is what I've put together: $(function() { $("#moreAdd").click(function() { var dataString = []; var selector = '#repeat0'; var row; for(var i=0;$ ...

Establish an HttpOnly cookie using JavaScript

Is it possible to convert a non-HttpOnly cookie into an HttpOnly cookie using JavaScript? ...

Encountering 'Illegal Invocation' error while running a basic script

Exploring the Speech Recognition API has been on my to-do list, so I decided to create a simple page that initiates recognition when clicking on the body element. Here is a snippet from my scripts.js file: var recognition = new window.webkitSpeechRecognit ...

Retrieve information from a database in real-time using Ajax without needing to set a refresh interval

Currently, I have been working on jquery/ajax requests and have managed to create an ajax request that retrieves data from a database. However, the issue at hand is that I am continuously utilizing window.setInterval() to refresh this function every x seco ...

Creating Ajax form partials in Rails for multiple models allows for more dynamic and efficient

Having this AJAX code snippet (sourced from: ), which is used across various views like new.html.erb and edit.html.erb, I am looking to avoid redundancy by utilizing partials: app/views/cities/_state_city_form.html.erb <p> State: <%= select(:s ...

Troubleshooting issue with jquery.i18n.properties functionality

I am encountering an issue with implementing jQuery internationalization. I have included the files jquery.i18n.properties.js, jquery.i18n.properties-min.js, and jquery-min.js in my resources folder. In my jsp, I have added the following code: <script ...

Can I incorporate NodeJS modules such as "oauth" into my Firefox extension?

I am diving into the world of Firefox addons for the first time. My project entails making calls to Twitter's APIs, which means I require an oauth library to kick things off. After some research, I came across an existing library in the npm package r ...

Jolt - Self-contained entity- Iteratively substitute property identifiers

I'm new to working with Jolt. I have a JSON payload that represents logical conditions using AND/OR, and it can include an array of conditions called "conditionPredicates", leading to nested conditions like AND(OR(a, b ,c), OR(d,e)). I'd like to ...

Is there a way to obtain the JSON array that begins with a nameless array?

How can I access the array to retrieve the text portion? The array structure is a bit confusing, and I'm not sure how to extract the text from it. [ { "textProns": [], "sourceDictionary": "ahd-legacy", "exampleUses": [], "relatedWords ...

position the tooltip within the ample available space of a container in an angular environment

In my editor, users can create a banner and freely drag elements within it. Each element has a tooltip that should appear on hover, positioned on the side of the element with the most space (top, left, bottom, right). The tooltip should never extend outsid ...

Guidelines on creating actionable functions using JavaScript

Having trouble connecting the form to the database and looking for a solution. This is the HTML form that I've been working on, attempting both POST and GET methods. <form id="register" action="script/register.js" method="post"> <label for= ...

Is it possible for javascript to show the user's current location on a google map without using a KML layer?

I need help with loading a KML file using JavaScript and adding a marker to the map at the user's current location. The code I have been working on works fine, but it seems to be missing the geolocation check for the current position. How can I proper ...

Troubleshooting: Issue with WCF service not processing POST requests

I encountered an issue when attempting to call a WCF service using AJAX from another project. The error message displayed was: The server encountered an error processing the request. The exception message is 'The incoming message has an unexpected me ...

How can I properly retrieve a request in node.js?

I seem to be quite curious lately ;) I've been making progress in developing my web chat system. Finally, I was able to make it work! My main query was how to input text into the textarea and have the message sent to the server upon pressi ...

Discovering identical objects in two arrays in Angular using TypeScript is a breeze

I've hit a roadblock with a TypeScript problem in my Angular service. I have an array of ingredients: private ingredients: Ingredient[] = [ new Ingredient('farina', 500), new Ingredient('burro', 80), new Ingredient('ucc ...

What is the correct method for iterating through this array of objects and eliminating those with either null or empty item.text values?

Currently, I am working with the following Array: const contactInfo = computed(() => { return [ { id: 'address', icon: 'detail/clubLocation', text: `${props.data.contactInfo.address}` ...

What is the process of converting an image taken with the 'react-camera-pro' into a byte array?

I am in the process of capturing an image using a camera through 'react-camera-pro' and I need to figure out how to convert the captured image into a byte array. Here is the snippet of code that I am working with: const camera = useRef(null); ...

Is there a way to swap out the original text with the ajax response text?

Upon receiving the ajax response, it replaces the initial text if the checkbox is ticked. How can I achieve the opposite? Revert back to the original text when the user unticks the checkbox? $.ajax({ type: 'POST', url: 'index.php?r=re ...

Abbreviating Column Labels in Google Visualization

Is there a way to use the google visualization API to display column headers in an abbreviated form in a table, but show the full labels in a pie chart using the same dataset? Check out this snippet of JavaScript: //create the dashboard and table chart ...

The setInterval function is malfunctioning

If I have the following function: function check(){ alert("Welcome"); } window.onload = check(); setInterval("check();", 5000); However, it is not working properly. Oddly enough, when I refresh the page, it works as intended. How can I resolve this i ...