Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple AngularJS, AJAX, and ASP.NET MVC example

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!

like image 497
Jason Avatar asked Jul 02 '14 14:07

Jason


People also ask

Can we use AngularJS with ASP.NET MVC?

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.

Can we use Ajax in 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.

What is Ajax in ASP NET MVC?

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.


1 Answers

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;
     });
});
like image 183
ahmed alnahas Avatar answered Sep 21 '22 14:09

ahmed alnahas