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:
$http
method with something like $scope.color = 'purple';
then my view renders the word "purple" as expected. {{color}}
to {{color()}}
but it made no difference.JsonResult
and returning Json("red", JsonRequestBehavior.AllowGet);
but this made no difference either.I appreciate your help!
AngularJS with Visual Studio Click on ASP.NET Web Application, rename the application and hit “ok” button at bottom right. Choose empty template in next window and click on “ok” button. It will take a while to load a sample empty project. Now the first thing we need to do is register AngularJS.
The AngularJS provides a control service named as AJAX – $http, which serves the task for reading all the data that is available on the remote servers. The demand for the requirement of desired records gets met when the server makes the database call by using the browser. The data is mostly needed in JSON format.
As you might be knowing, Ajax is a shorthand for Asynchronous JavaScript and XML. The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features.
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;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With