【发布时间】: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