5

I would like to see an extremely minimalistic example of AngularJS making an AJAX call to an ASP.NET MVC action method. I have tried to do this myself with no success. Here is my example code...

The MVC action method...

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

The 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>

The 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 replace the $http method with something like $scope.color = 'purple'; then my view renders the word "purple" as expected.
  • If I leave everything as is but replace the AngularJS with jQuery, everything works as expected (I get "red").
  • I tried changing {{color}} to {{color()}} but it made no difference.
  • I tried changing the action method to a JsonResult and returning Json("red", JsonRequestBehavior.AllowGet); but this made no difference either.

I appreciate your help!

1 Answer 1

8

add $http to your controller

colorApp.controller('ColorController', function ($scope,$http) {
      $http({
                url: '/home/color',
                method: 'GET'
           }).success(function (data, status, headers, config) {
    $scope.color = data;
     });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! It's that simple. Thanks a ton! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.