Controller 返回数据,但我无法在 HTML 文件中迭代它。但是,使用表达式 {{phones}} 会直接显示返回的数据。我相信数据是以字符串而不是 json 的形式返回的。我期待与循环中返回的所有数据相对应的名称和片段。
<body ng-app="phonecatApp" ng-controller="PhoneListCtrl" >
Search: <input ng-model="query">
Sort By:
<select ng-model="orderByFilter">
<option value="name">Alphabetical</option>
<option value="age">Numerical</option>
</select>
<ul>
<li ng-repeat="phone in phones | orderBy:orderByFilter">
<span>{{phone.name}}</span>
<span>{{phone.snippet}}</span>
</li>
</ul>
<script src="~/Scripts/AngularScript.js"></script>
</body>
Angular js 脚本
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
$http.get('Home/GetJson').success(function (data){
$scope.phones = data;
});
});
Controller 操作方法
public JsonResult GetJson()
{
string variablename = "[{'name': 'Nexus S','snippet': 'Fast just got faster with Nexus S.', 'age': 1}]";
return Json (variablename, JsonRequestBehavior.AllowGet);
}
最佳答案
由于您已经拥有 JSON 格式的数据,因此不需要使用方法 Json
,因为它会在幕后再次序列化对象。您可以使用方法 Content
来代替:
public ActionResult GetJson()
{
string variablename = "[{'name': 'Nexus S','snippet': 'Fast just got faster with Nexus S.', 'age': 1}]";
return Content(variablename);
}
或者,您可以创建一个对象,并允许方法 Json
序列化该对象,而不是提供硬编码数据:
public ActionResult GetJson()
{
var resultObject = new object [] {
new {
name="Nexus S",
snippet= "Fast just got faster with Nexus S.",
age= 1
}
};
return Json (resultObject, JsonRequestBehavior.AllowGet);
}
关于javascript - $http.get 请求成功时获取字符串而不是 json (Angular JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676437/