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
$httpmethod 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
JsonResultand returningJson("red", JsonRequestBehavior.AllowGet);but this made no difference either.
I appreciate your help!