0

I'm trying to follow an example from LinkedIn but having the following problems: 1. I try to call localhost:portname/Values/GetStates but instead of loading the page it asks me to download the json file. 2. When I used F12, it didn't show me Angular and other references I added to my project, can't understand why is it so? I tried including references at the top of the page like this:

<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/Controllers/AngularController.js"></script>
<script src="~/Scripts/Services/AngularService.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />

and using:

  bundles.Add(new ScriptBundle("~/Scripts/angularscripts").Include(
            "~/Scripts/angular.js",
            "~/Scripts/AngularController.js",
            "~/Scripts/AngularService.js"));

and then including the bundle reference like this:

@section Scripts
{
    @Scripts.Render("~/Scripts/angularscripts")

}

but didn't work either.

My code is simple:

 public class ValuesController : ApiController
{
    [HttpGet]
    public string GetStates()
    {
        List<States> states = new List<States>();
        var state = new States();

        state.Id = 1;
        state.Name = "NSW";
        states.Add(state);

        state.Id = 2;
        state.Name = "QLD";
        states.Add(state);

        state.Id = 3;
        state.Name = "VIC";
        states.Add(state);

        state.Id = 4;
        state.Name = "WA";
        states.Add(state);

        var result = JsonConvert.SerializeObject(states);
        return result;
    }

    [HttpPost]
    public string GetResult(States state)
    {
        var result = "State name is " + state.Name;
        result = JsonConvert.SerializeObject(result);
        return result;

    }

}

and Angular code is: AngularService.js

AngularModule.service('ApiCall', ['$http', function ($http) {
var result;

this.GetApiCall = function (controllerName, methodName) {
    result = $http.get('api/' + controllerName + '/' + methodName).success(function (data, status) {
        result = (data);
    }).error(function () {
        alert("Some problem in calling the service");
    });
    return result;
};

this.PostApiCall = function (controllerName, methodName, obj) {
    $http.post('api/' + controllerName + '/' + methodName).success(function (data, status) {
        result = (data);
    }).error(function () {
        alert("Some problem in calling the service");
    });
    return result;
};

}]);

AngularController.js

var AngularModule = angular.module('App', []);

AngularModule.controller('AppController', function ($scope, $http, ApiCall)     {
    $scope.message = "This is a test";
    alert('App Controller');

    var result = ApiCall.GetApiCall("Values", "GetStates").success(function (data) {
        alert('data');
        var result = $.parseJSON(JSON.parse(data));
        $scope.StateList = result;
    });

    $scope.btnPostCall = function () {
        var obj = {
            'Name': 'NSW'
        };

        var result = ApiCall.PostApiCall("Values", "GetResult", obj).success(function (data) {
            var result = $.parseJSON(JSON.parse(data));
            $scope.message = result;
        });

    }

});

AngularService.js

AngularModule.service('ApiCall', ['$http', function ($http) {
var result;

this.GetApiCall = function (controllerName, methodName) {
    result = $http.get('api/' + controllerName + '/' + methodName).success(function (data, status) {
        result = (data);
    }).error(function () {
        alert("Some problem in calling the service");
    });
    return result;
};

this.PostApiCall = function (controllerName, methodName, obj) {
    $http.post('api/' + controllerName + '/' + methodName).success(function (data, status) {
        result = (data);
    }).error(function () {
        alert("Some problem in calling the service");
    });
    return result;
};

}]);

I run this project by appending 'api/values/getstates' to localhost. Any ideas ???

    }
}
sam
  • 391
  • 1
  • 5
  • 19
  • Hi sam, could you please post your controller. It seems your service code is duplicated, but I can't see your controller. – Leo Caseiro Jul 04 '16 at 06:15
  • @LeoCaseiro It's updated, I assume that my angular code is not called at all, it seems to me that only the web service's json data is being returned, please have a look – sam Jul 04 '16 at 23:47

2 Answers2

0

I faced similar issue when I was running angularjs application in internet explorer browser, but works fine in other browsers like Firefox and Chrome. In my case problem was that Internet Explorer's registry setting was not set to display json, so it was throwing out stream to download like any other file.

Please refer settings in following link if that works for you as well.

How can I convince IE to simply display application/json rather than offer to download it?

Community
  • 1
  • 1
barkat
  • 11
  • 2
0

Hi, This is full example you can figure out how to use service in your application.

        var app = angular.module("app", []);

app.controller("controller", ["$scope","ApiCall", function ($scope, apiCall) {
            var root = 'http://jsonplaceholder.typicode.com';

            apiCall.GetApiCall(root + "/posts").then(function(data) {
                $scope.posts = data;
            });

            $scope.post = function () {
                var command = {
                    title: 'maher',
                    body: 'test',
                    userId: 1
                }
                apiCall.PostApiCall(root + "/posts", command).then(function (response) {
                    console.log(response)
                    $scope.posts.push(response);
                });
            }

        }]);

        app.service("ApiCall", ["$http", "$q", function ($http, $q) {
            this.GetApiCall = function (api) {
                var deferred = $q.defer();

                $http({
                    method: "GET",
                    async: true,
                    url: api
                }).success(function (response) {
                    deferred.resolve(response);
                })
                    .error(function (error) {
                        console.error("HttpRestApp error:", error);
                        deferred.reject(error);
                    });
                return deferred.promise;
            };

            this.PostApiCall = function (api, data) {
                var deferred = $q.defer();

                $http({
                    method: "POST",
                    async: true,
                    data: data, 
                    url: api
                }).success(function (response) {
                    deferred.resolve(response);
                })
                    .error(function (error) {
                        console.error("HttpRestApp error:", error);
                        deferred.reject(error);
                    });
                return deferred.promise;
            };
        }]);
<!DOCTYPE html>
<html ng-app="app" ng-controller="controller as ctrl">
<head>
    <title></title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <h1>POST</h1>

    <button ng-click="post()">post</button>
  <small>check your console: check last record it will be post</small>

    <div class="clearfix"></div>
    <h1>GET</h1>
    <table class="table table-bordred">
        <tr ng-repeat="post in posts">
            <td>{{post.title}}</td>
        </tr>
    </table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

</body>
</html>
Maher
  • 2,517
  • 1
  • 19
  • 32
  • Hi @Maher What I am looking for is to get some data from WebApi, I saw your code's working, thanks for that but I need someone to identify my errors. – sam Jul 04 '16 at 23:48