0

I'm trying to get data from the controller something like this:

public IEnumerable<Custom> Search(string searchText = "")
    {
        return new[] { new Custom { Name = "a", Id = 1 }, new Custom { Name = "b", Id = 1 }, new Custom { Name = "c", Id = 3 } };
    }

But angular gives me this

m u s i c p o r t a l . C o n t r o l l e r s . C u s t o m [ ]

I tried add http.headers but nothing. My code:

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

musicportal.controller('SearchController', ['$scope', '$http', function ($scope, $http) {
$scope.answer = "awesome";

$scope.search = function (text) {
    $scope.answer = text;
    $scope.pms = [];                  
    $http.post('/Home/Search', { searchText: text }).
        success(function (data, status, headers, config) {              
            $scope.pms = data;
        });
    $scope.searchText = "";
}
}]);

1 Answers1

0

You should return data as json e.g.

public ActionResult Search(string searchText = "")
{
    return Json(new { Foo = "Hello" }, JsonRequestBehavior.AllowGet);
}

$http.post('/Home/Search', { searchText: text }).
        success(function (data, status, headers, config) {              
            $scope.pms = data.Foo;
        });

Now, in your case, you have a list, so you need to convert that into JSON. You can do that in ASP.NET MVC using JsonSerializer e.g.

public ActionResult Search(string searchText = "")
{
    string json = "";
    var items = new[] { new Custom { Name = "a", Id = 1 }, new Custom { Name = "b", Id = 1 }, new Custom { Name = "c", Id = 3 } };

    using (var writer = new StringWriter())    
    using (var jsonWriter = new JsonTextWriter(writer))
    {
        serializer.Serialize(jsonWriter, items);
        json = writer.ToString();
    }

    return Json(json, JsonRequestBehavior.AllowGet);
}

$http.post('/Home/Search', { searchText: text }).
            success(function (data, status, headers, config) {              
                $scope.pms = JSON.Parse(data);
            });

You may need to play about with this code, it's not perfect first time, but hopefully it will give you a head start.

Jason Evans
  • 28,906
  • 14
  • 90
  • 154