字符串而不是数据

时间:2015-03-11 20:14:39

标签: asp.net-mvc angularjs http-post

我正在尝试从控制器获取数据 像这样的东西:

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 } };
    }

但是角度给了我这个

  

米   ü   小号   一世   C   p   Ø   [R   Ť   一个   升   。   C   Ø   ñ   Ť   [R   Ø   升   升   Ë   [R   小号   。   C   ü   小号   Ť   Ø   米   [   ]

我尝试添加http.headers但没有。 我的代码:

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 个答案:

答案 0 :(得分:0)

您应该将数据作为json返回,例如

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;
        });

现在,在您的情况下,您有一个列表,因此您需要将其转换为JSON。您可以使用JsonSerializer例如

在ASP.NET MVC中执行此操作
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);
            });

你可能需要玩这个代码,它不是第一次完美,但希望它会给你一个良好的开端。

相关问题