我有以下Javascript:
$(document).ready(function () {
$.getJSON("api/products/",
function (data) {
$.each(data, function (key, val) {
// Format the text to display.
var str = val.Name + ': $' + val.Price;
// Add a list item for the product.
$('<li/>', { text: str })
.appendTo($('#products'));
});
});
});
我的问题是产品列表没有显示。我有另一个功能可以搜索列表中的单个项目并且能够显示这些项目,但为什么这不起作用?
这是存储信息的类:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
这是控制器:
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public Product GetProductById(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return product;
}
public IEnumerable<Product> GetProductsByCategory(string category)
{
return products.Where(
(p) => string.Equals(p.Category, category,
StringComparison.OrdinalIgnoreCase));
}
}
我是 ASP.NET 的初学者,所以请让我知道我做错了什么。