4

I'm fairly new to C# and i'm completely stumped as to what I should be doing next to be processing inputs from a user inside of an input form I've created with Bootstrap and Html along with a AngularJS controller.

Every time I try to return values with my Get methods for my api, my whole controller breaks.

I've read so many tutorials and know-hows on RESTful api web methods and i'm beginning to confuse myself far too much and over thinking it, because I understand it's a simple process.

Here is the code for my Controller below:

public class FeedbackController : ApiController
    {
        // GET: api/Feedback
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Feedback/
        public string (Feedback id);
        {

        }

        // POST: api/Feedback
        public void Post([FromBody]Feedback value)
        {

        }

        // PUT: api/Feedback
        public void Put( [FromBody]Feedback value)
        {
            var test = value.FeedbackRating;
        }

        // DELETE: api/Feedback/
        public void Delete(Feedback id)
        {
        }
        public string post([FromUri]Feedback value)
        {
            return "Put returning:  " + value;
        }

//angular js
       commonModule.controller('feedbackController', ['$scope', '$modal',                    '       $timeout', 'authenticationService',
         function ($scope, $modal, $timeout, authenticationService) {

      var init = function () {
          $scope.feedbackPopup();
      }

      $scope.feedbackPopup = function () {

          var modalInstance = $modal.open({
              templateUrl: '/Scripts/app/common/views/popup.tpl.html',
              resolve: {

              },
              controller: function ($scope, $modalInstance) {

                  $scope.close = function () {
                      $modalInstance.close();
                  };

                  $scope.submitFeedback = function () {
                      $scope.feedback = {

                         FeedbackRating: 1,
                          FeedbackSubject: 1,
                          FeedbackUpload: 1,
                          FeedbackDescription:1

                      };

                      authenticationService.submitFeedback($scope.feedback).then(
                      // Success Handler
                       function (result) {
                            $modalInstance.close();
                            $scope.message = "Feedback submitted";
                            $timeout(function () {
                                $scope.message = "";
                            }, 3000);
                      },
                      // Failure Handler
                      function () {
                            $scope.message = "Error updating specialization";
                      });
                  }
              }
          });
      }

      init();

       }]);
   })();


Feedback class

{
   public class Feedback
   {
    public int FeedbackRating { get; set; }
    private string EncryptedHexPuid { get; set; }
    public string FeedbackDescription { get; set; }
    public string FeedbackSubject { get; set; }
    }
}
8
  • Can you post your Angular controller code? Specifically your $http call, but preferably more Commented May 5, 2015 at 17:54
  • When you say every time I try to return values with my Get methods for my api, my whole controller breaks. do you mean your angular.js controller that is making the $http call or do you mean your wep api controller that is handling the request? Commented May 5, 2015 at 17:54
  • When you hit your api URL's in the browser, do you get the expected response? Commented May 5, 2015 at 17:55
  • I'll post my Angular controller. Commented May 5, 2015 at 18:03
  • And sgwatstack, I mean the code just doesn't run anymore and the posts break. Meaning there is a code issue. The issues that arise are expected class, delegate, enum, interface, or struct.' Commented May 5, 2015 at 18:04

2 Answers 2

1

Here are the important parts of setting up an app using Angular.js and Asp.Net Web Api

index.html

<!doctype html>
<html class="no-js" lang="" ng-app="demo">
<head>
    <meta charset="utf-8">
    <base href="/">
</head>
<body ng-controller="MainController as vm'>
    <h1>Demo</h1>
    <div>{{vm.value[0]}}</div>
    <div>{{vm.value[1]}}</div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>
    <script src="js/app/app.js"></script>
</body>
</html>

app.js

(function () {
    'use strict';

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

    app.config(config);

    function config($locationProvider, $routeProvider) {
        $locationProvider.html5Mode(true);
    }

    var controller = angular
        .module('demo')
        .controller('MainController', MainController);

    function MainController($http) {
        var vm = this;
         // Here localhost is where your asp.net web api server is serving from
         // The /api/feedback is the url that the FeedbackController
         // in your asp.net web api project answers requests to
         // It returns a json array of two strings
         $http.get('http://localhost:12312/api/feedback').
            success(function (data, status, headers, config) {
                console.log("Success: " + data);
                vm.values = data;
            }).
            error(function (data, status, headers, config) {
                console.log("Error: " + data);
                vm.error = data;
}());

Here is FeedbackController.cs

public class FeedbackController : ApiController
{
    // GET: api/Feedback
    public IEnumerable<Feedback> Get()
    {
        return new Feedback[] { new Feedback(), new Feedback() };
    }

    // GET: api/Feedback/5
    public Feedback Get(int id)
    {
        return new Feedback();
    }

    // POST: api/Feedback
    public IHttpActionResult Post([FromBody]Feedback value)
    {
        return Ok(value);
    }

    // PUT: api/Feedback/5
    public IHttpActionResult Put(int id, [FromBody]Feedback value)
    {
        return Ok(value);
    }

    // DELETE: api/Feedback/5
    public void Delete(int id)
    {
    }
}

Notice I am returning IHttpActionResults from my Post and Put methods. There are more appropriate result codes to return for these actions but this will get you going.

Note: I tested this code out and it all works correctly when building the web api app with the asp.net web api template in visual studio 2013.

Sign up to request clarification or add additional context in comments.

2 Comments

This compiled correctly in my code! I think my issue was I didn't understand these completely. This was a great help, what steps should I take next time I approach something like this to avoid confusion?
@Royalgambino I would recommend walking through the web api tutorials ( asp.net/web-api/overview/getting-started-with-aspnet-web-api ). This book ( apress.com/9781484201107 ) has also helped me understand this framework, coming from an MVC background. This course on MVA ( microsoftvirtualacademy.com/training-courses/… ) is pretty good at covering the basics of HTTP requests/responses in web api. Just knowing REST will help with concepts, but not syntax and execution with an asp.net application. The above will help with those.
0

Just based on the limited information you have provided, here's an example angular service that will get the values from your asp.net controller:

angular.module('MyModule', [])
     .service('feedbackService', ['$http', function($http){
         this.getFeedback = function(){
               return $http.get('/api/Feedback');
      }
}]);

angular.module('MyModule',[])
     .controller('pageCtrl', ['$scope','feedbackService', function(scope, feedbackService){
          $scope.$watch('someObj.someProperty', function(){
               feedbackService.getFeedback()
               .then(function(res){ 
                            // Success 
                     }, 
                     function(err) { 
                           // error 
                     }
               );
          }
}]);

Considering this is a REST Api, you may want to use $resource instead of $http, as it's more intuitive when working with RESTFul services. More details:

https://docs.angularjs.org/api/ngResource/service/$resource

2 Comments

So i'm assuming the issue is with my angular methods and not my c#?
Depends, if you are getting an exception server side when your ajax call goes out (check the network tab in the browser dev tools is returning an error status of 500/404/etc). If you are getting a 500 error, you have a problem with your asp.net code. If you get a 404, you likely have a routing problem, or have the wrong URL in your angular code. If you are not seeing any requests, check for javascript errors which would indicate your angular code is the problem.

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.