我有一个ApiController,执行以下操作:
[HttpGet]
public HttpResponseMessage SearchPersons(string data)
{
if (!_isAuthenticated) { return Request.CreateResponse(HttpStatusCode.Unauthorized); }
var results = new List<PersonSearchResult>();
results.Add(new PersonSearchResult() { Name = "Mr. test", Sex = "male", Married = false });
results.Add(new PersonSearchResult() { Name = "Mrs. test", Sex = "female", Married = true });
results.Add(new PersonSearchResult() { Name = "Dr. test", Sex = "female", Married = false });
return Request.CreateResponse(HttpStatusCode.OK, results, Request.GetConfiguration());
}
如果获得授权,它会返回一个PeopleSearchResults列表,它看起来像这样:
[
{
"name": "Mr. test",
"sex": "male",
"married": false
},
{
"name": "Mrs. test",
"sex": "female",
"married": true
},
{
"name": "Dr. test",
"sex": "female",
"married": false
}
]
但我希望它看起来更像这样:
{
"results": [{
"name": "Mr. test",
"sex": "male",
"married": false
}, {
"name": "Mrs. test",
"sex": "female",
"married": true
}, {
"name": "Dr. test",
"sex": "female",
"married": false
}]
}
我可以实现吗?
如果没有,我如何使用jQuery循环第一个结果? 现在我试过这样,但是IntelliSense告诉我我不能循环它,没有.Count可用于“数据”。 所以我认为最好的解决方案就是将它包装成我想要的示例所示,这样我就可以循环data.results,然后应该有一个.Count。
// search button action assignment:
$("#search-button").click(function () {
var search = $("#search-input").val();
if (search.trim() != "") {
var ajax = $.ajax({
dataType: "json",
url: "/api/search/SearchPersons/" + search
});
ajax.done(function (data) {
console.log("Done!");
console.log(data);
});
ajax.fail(function (data) {
console.log("Fail!");
console.log(data);
});
} else {
console.log("Empty search input value.");
$("#search-input").focus();
}
});
答案 0 :(得分:2)
我可以实现吗?
当然,你可以。首先编写一个视图模型以反映所需的结构:
public class MyViewModel
{
public List<PersonSearchResult> Results { get; set; }
}
然后返回此视图模型而不是原始列表:
var model = new MyViewModel();
model.Results = results;
return Request.CreateResponse(HttpStatusCode.OK, model, Request.GetConfiguration());
如果没有,我如何使用jQuery循环第一个结果?现在我试过了 像这样,但IntelliSense告诉我,我无法循环它,没有.Count是 可在“数据”上找到。
.Count
是ICollection<T>
类的.NET属性。在javascript数组中,您要查找的相应属性称为.length
。所以只要确保如果你想在javascript中循环返回的集合,你就是使用了正确的javascript属性:
ajax.done(function (data) {
for (var i = 0; i < data.length; i++) {
var item = data[i];
console.log(item.name);
console.log(item.sex);
console.log(item.married);
}
});
所以我认为最好的解决方案就是如图所示包装它 我想要的例子,所以我可以循环data.results,然后应该有一个 .Count之间。
哦,不,data.results
将是完全相同的数组,就像你没有将它包装在视图模型中一样。你仍然需要使用正确的javascript属性来循环它:
ajax.done(function (data) {
for (var i = 0; i < data.results.length; i++) {
var item = data.results[i];
console.log(item.name);
console.log(item.sex);
console.log(item.married);
}
});
这是good overview
数组如何在javascript中工作,我建议你阅读。