【问题标题】:How to display an object's data on client side using json?如何使用json在客户端显示对象的数据?
【发布时间】:2015-01-16 08:25:41
【问题描述】:
  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>

【问题讨论】:

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


    【解决方案1】:

    试试

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

    【讨论】:

      【解决方案2】:

      如果数据是 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'));
                      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-31
        • 2012-07-24
        • 2021-04-22
        • 2015-01-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多