1

我有以下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 的初学者,所以请让我知道我做错了什么。

4

1 回答 1

1

我认为您的意思是使用文本作为创建 <li> 节点的初始 jQuery 选择器的方法。

将第二个参数传递给 $() 实际上会产生一个“上下文”,它将尝试限制选择器从哪里开始。请参阅:http ://api.jquery.com/jQuery/#jQuery1/

http://jsfiddle.net/A4tk9/

$(function() {

    var data = [{ Name: 'test1', Price: 1000}, { Name: 'test2', Price: 25}];

    $.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'));   
    });

});
于 2013-05-21T19:46:01.437 回答