2015-01-16 2 views
0
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, отображается. Но когда дело доходит до отображения деталей объекта, он передает символ по символу, если возвращается как сериализованная строка.Как отобразить данные объекта на стороне клиента с помощью 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> 

ответ

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')); 
         }); 
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')); 
       }); 
Смежные вопросы