1

I'm trying to pass the parameter from Angular to ASP.NET MVC Controller and I need some help with this. First I had problems even with passing the parameter because I always had null in my action method in MVC controller. I already solved it but another problem is with getting data from MVC and displaying it with Angular in the right html template. I tried a lot to solve this problem, I was looking for any solution but the result is still the same. Here is my code:

MVC Controller (GenreController)

public JsonResult GetGameList(string genrename)
    {
        if (genrename != null)
        {
            try
            {
                var genre = db.Genres.Include("Games").Where(x => x.Name.ToLower() == genrename.ToLower()).SingleOrDefault();
                var gameslist = genre.Games.ToList();
                return Json(gameslist, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

                throw new Exception("Something bad happened!", ex);
            }
        }
        else
        {
            return Json(null);
        }

    }

Here is my angularjs app:

var app = angular
    .module('app', ['ngRoute', 'GenreController', 'HomeController', 'AccountController'])
    .config(function ($routeProvider) {
        $routeProvider
            .when('/genres/:genrename', {
                templateUrl: 'templates/genre.html',
                controller: 'GenreCtrl'
            })
            .when('/account/login', {
                templateUrl: 'templates/login.html',
                controller: 'AccountCtrl'
            })
            .when('/account/register', {
                templateUrl: 'templates/register.html',
                controller: 'AccountCtrl'
            })
            .when('/', {
                templateUrl: 'templates/home.html',
                controller: 'HomeCtrl'
            })
            .otherwise({ redirectTo: '/' });
    });

GenreCtrl:

angular.module('GenreController', [])
       .controller('GenreCtrl', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
           $scope.genres = {};
           $scope.gameslist = {};
           $scope.msg = "AngularJS";

           //get genres for navbar
           $http.get('/Home/GetGenres').success(function (data) {
               $scope.genres = data;
           }).error(function (err) {
               console.log(err);
           });

           //here is probably the problem
           var response = $http({
               method: "get",
               url: "/Genre/GetGameList",
               params: {
                   genrename: $routeParams.genrename
               },
               success: function (data) {
                   $scope.gameslist = data;
               }
           });

           $scope.genrename = $routeParams.genrename; 
       }]);

Debugging and 2 console errors:

Debugging

In the html template I'm just doing something like this for see if I can get the data or not

<div ng-repeat="game in gameslist">
    <h1>{{game.Price}}</h1>
</div>

I think it might be something wrong with success in response but maybe you guys have some solution for this.

//Update, here is the server side debugging:

Server-side-debugging

//Update - the problem solution

Okay, so I spent a lot of time on it but it's finally working. Maybe not exactly what I wanted but for now that's okay. First I had to add JsonConvert to my server side action method. It's returning this object with JSON AllowGet. Then I added GetGenreByName action method that returns the name of specified genre (you can do this also in GetGameList action method if you want instead of creating seperated action but I think this is just better to have GetGenreByName action seperated from others). Also in Angular controller I changed my success to then and I had to parse my data using JSON.parse. Here is my working code:

MVC Controller

[HttpGet]
        public JsonResult Get(string genrename)
        {
            try
            {
                var results = GetGenreByName(genrename);
                if (results == null)
                {
                    return Json(null);
                }
                else
                {


    var list = JsonConvert.SerializeObject(results.Games, Formatting.None, new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                });

                 return Json(list, JsonRequestBehavior.AllowGet);
            }
        }
        catch (Exception ex)
        {
            return Json(ex, JsonRequestBehavior.AllowGet);
        }
    }


public Genre GetGenreByName(string gname)
{
    return db.Genres.Include("Games").Where(x => x.Name == gname).FirstOrDefault();
}

Angular controller:

   $http({
       url: '/Genre/Get',
       params: {
           genrename: $routeParams.genrename
       },
       method: 'get'
   }).then(function (response) {
       $scope.list = JSON.parse(response.data);
   });

and ng-repeat to check if all is working.

<div ng-repeat="game in list">
    <h2>{{game.GameTitle}}</h2>
</div>
7
  • When you debug your server code. At which line does it crash? Commented Mar 7, 2016 at 16:02
  • Add a breakpoint at the catch{...} block Commented Mar 7, 2016 at 16:04
  • Server side is not getting any errors. Just these 2 errors in the console. Commented Mar 7, 2016 at 16:04
  • But http status 500 means that the server controller crashed. You have the flag [AllowGet] ? Commented Mar 7, 2016 at 16:07
  • 1
    Hint try typing into the address line of Firefox http//localhost:58867/Genre/GetGameList?genrename=Sport . Firefox know will show you the JSON data, if the server does not crash. Commented Mar 7, 2016 at 16:13

0

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.