如何使用json在客户端显示对象的数据?

时间:2015-01-16 08:25:42

标签: jquery asp.net json asp.net-web-api

  public class ProductController : 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 string GetProductById(int id)
    {
        Product product = products.FirstOrDefault((p) => p.Id == id);
        if (product == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

        //var json = new JavaScriptSerializer().Serialize(product);

        string json = JsonConvert.SerializeObject(product);
        return json;
        //return product;
    }

    public IEnumerable<Product> GetProductsByCategory(string category)
    {
        return products.Where(
            (p) => string.Equals(p.Category, category,
                StringComparison.OrdinalIgnoreCase));
    }
}

以下代码正在消费者应用程序中使用。我在客户端收到一个未定义的数据但是当传递已经是json格式的列表时会显示。但是当涉及到显示的对象细节时,如果作为序列化字符串返回,则逐个字符地传递。

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master"  AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WEbAPIConsumer._Default" %>

   <asp:Content runat="server" ID="FeaturedContent"     ContentPlaceHolderID="FeaturedContent">
  <script src="Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
          alert("hello");          
            function getProducts() {
               $.getJSON("http://localhost:51641/api/product/1",
                function (data) {
                    $('#products').empty(); // Clear the table body.
                    // Loop through the list of products.
                    //alert(data);
                    $.each(data, function (key, val) {
                        // Add a table row for the product.
                        alert(val.Name);
                        var row = '<td>' + val.Name + '</td><td>' +   val.Price + '</td>';
                        $('<tr/>', { html: row })  // Append the name.
                            .appendTo($('#products'));
                    });
                });
        }
        $(document).ready(getProducts);
    });
</script>

</asp:Content>
       <asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <h2>Products</h2>
   <table>
      <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody id="products">
    </tbody>
</table>
</asp:Content>

2 个答案:

答案 0 :(得分:0)

尝试

   $.each(data,function(idx, obj) {
                            // Add a table row for the product.
                            alert(obj.Name);
                            var row = '<td>' + obj.Name + '</td><td>' +   obj.Price + '</td>';
                            $('<tr/>', { html: row })  // Append the name.
                                .appendTo($('#products'));
                        });

答案 1 :(得分:0)

如果数据以json字符串形式出现,则将数据解析为json。

data=$.parseJSON(data);//this line parses the data into json
$.each(data, function (key, val) {
                    // Add a table row for the product.
                    alert(val.Name);
                    var row = '<td>' + val.Name + '</td><td>' +   val.Price + '</td>';
                    $('<tr/>', { html: row })  // Append the name.
                        .appendTo($('#products'));
                });