A simple example of AngularJS, AJAX, and ASP.NET MVC

I would like to see an extremely minimalist AngularJS example creating an AJAX call for an ASP.NET MVC action method. I tried to do it myself without success. Here is my sample code ...

MVC Action Method ...

public string Color()
{
    return "red";
}

HTML ...

<!DOCTYPE html>    
<html ng-app ="ColorApp">
<head>
    <title>ColorApp</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
    <script src="/Scripts/app.js"></script>
</head>
<body>
    <div ng-controller="ColorController">
        {{color}}
    </div>
</body>
</html>

JavaScript ...

var colorApp = angular.module('ColorApp', []);

colorApp.controller('ColorController', function ($scope) {

    $http({
        url: '/home/color',
        method: 'GET'
    }).success(function (data, status, headers, config) {
        $scope.color = data;
    });

});

Some things to consider:

  • If I replaced the method $httpwith something like $scope.color = 'purple';, then my view will display the word purple, as expected.
  • If I leave everything as it is, but replace AngularJS with jQuery, everything works as expected (I get "red").
  • I tried changing {{color}}to {{color()}}, but that didn't matter.
  • I tried to change the method of action to JsonResultand return Json("red", JsonRequestBehavior.AllowGet);, but that didn't matter either.

I appreciate your help!

+4
1

$http

colorApp.controller('ColorController', function ($scope,$http) {
      $http({
                url: '/home/color',
                method: 'GET'
           }).success(function (data, status, headers, config) {
    $scope.color = data;
     });
});
+8

Source: https://habr.com/ru/post/1546869/


All Articles