我正在使用OData& amp; Web API通过ajax。我尝试使用OData过滤器属性从服务器端进行分页。这是我的Controller代码。
[RoutePrefix("OData/Products")]
public class ProductsController : ODataController
{
private List<Product> products = new List<Product>
{
new Product() { Id = 1, Name = "Thermo King MP-3000", Price = 300, Category = "Thermo King" },
new Product() { Id = 2, Name = "Thermo King MP-4000", Price = 500, Category = "Thermo King" },
new Product() { Id = 3, Name = "Daikin Decos III c", Price = 200, Category = "Daikin" },
new Product() { Id = 4, Name = "Daikin Decos III d", Price = 400, Category = "Daikin" },
new Product() { Id = 5, Name = "Starcool RCC5", Price = 600, Category = "Starcool" },
new Product() { Id = 6, Name = "Starcool SCC5", Price = 700, Category = "Starcool" }
};
[EnableQuery(PageSize=2)]
public IQueryable<Product> Get()
{
return products.AsQueryable<Product>();
}
//[EnableQuery]
//public SingleResult<Product> Get([FromODataUri] int id)
//{
// var result = products.Where(x => x.Id.Equals(id)).AsQueryable();
// return SingleResult.Create<Product>(result);
//}
[EnableQuery]
public Product Get([FromODataUri] int id)
{
return products.First(x => x.Id.Equals(id));
}
}
这是我的javascript代码:
<script type="text/javascript">
$(document).ready(function () {
var apiUrl = "http://localhost:56963/OData/Products";
$.getJSON(apiUrl,
function (data) {
$("#div_content").html(window.JSON.stringify(data));
}
);
//$.get(apiUrl,
//function (data) {
// alert(data[0]);
// $("#div_content").html(data);
//});
});
</script>
OData的响应是JSON结果,如:
{&#34; @ odata.context&#34;:&#34; http://localhost:56963/OData/ $元数据#产品&#34;&#34;值&#34;:[{&#34;标识&# 34;:1,&#34;名称&#34;:&#34; Thermo King MP-3000&#34;,&#34;价格&#34;:300,&#34;类别&#34;:&#34 ; Thermo King&#34;},{&#34; Id&#34;:2,&#34; Name&#34;:&#34; Thermo King MP-4000&#34;,&#34; Price&#34; :500,&#34;类别&#34;:&#34; Thermo King&#34;}],&#34; @ odata.nextLink&#34;:&#34; http://localhost:56963/OData/Products?$ skip = 2& #34;}
我试图获得&#34; @ odata.nextLink&#34;但失败了,没有办法得到&#34; odata.nextLink&#34;通过&#34;数据。@ odata.nextLink&#34;来自javascript。
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
将字符串解析为json后,数据['@ odata.nextLink']可以正常工作:
var data = '{"@odata.context":"http://localhost:56963/OData/$metadata#Products","value":[{"Id":1,"Name":"Thermo King MP-3000","Price":300,"Category":"Thermo King"},{"Id":2,"Name":"Thermo King MP-4000","Price":500,"Category":"Thermo King"}],"@odata.nextLink":"http://localhost:56963/OData/Products?$skip=2"}';
data = JSON.parse(data);
alert(data['@odata.nextLink']);