【问题标题】:String instead of data字符串而不是数据
【发布时间】:2015-03-11 20:14:38
【问题描述】:

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

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

但是角度给了我这个

米 你 s 一世 C p ○ r 吨 一种 l . C ○ n 吨 r ○ l l e r s . C 你 s 吨 ○ 米 [ ]

我尝试添加 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 = "";
}
}]);

【问题讨论】:

  • 看看这个post能不能帮到你。
  • 您是否从该控制器调用中获取 JSON?
  • 我尝试在 angular.foreach 视图中使用 $scope.pms

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


【解决方案1】:

您应该将数据返回为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。你可以在 ASP.NET MVC 中使用JsonSerializer 来做到这一点,例如

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

您可能需要使用此代码,第一次并不完美,但希望它能给您一个良好的开端。

【讨论】:

  • 非常感谢,这对我有帮助
  • 很高兴我的回答对您有所帮助:)
猜你喜欢
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多