我有一个简单的页面,它需要一个ID来从数据库返回的产品列表中找到特定产品,然后在html页面中显示此产品。我能够看到我使用/ api/products/12345时期望看到的JSON,但是当我尝试从Index.cshtml页面查询数据时,我找回了结果 - > undefined:$ undefined在我的页面中。我将通过Product类和我的html页面。请注意,所有产品的显示都完美呈现。
public class Product
{
public int ID { get; set; }
public string ProductDescription { get; set; }
public string UnitOfMeasure { get; set; }
public decimal MSRP { get; set; }
public string Category { get; set; }
public int CategoryID { get; set; }
public string ZipCode { get; set; }
}
这是我Index.cshtml页
.:: Web API ::.$(document).ready(function() {
// Send an AJAX request - the second parameter is a callback function that is invoked when the request successfully completes.
$.getJSON("api/products/",
function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, val) {
// Format the text to display.
var str = val.ProductDescription + ': $' + val.MSRP;
// Add a list item for the product.
$('
', { html: str }).appendTo($('#products'));});
});
});
function find() {
var id = $('#prodId').val();
// Again, we call the jQuery getJSON function to send the AJAX request, but this time we use the ID to construct the request URI.
$.getJSON("api/products/" + id,
function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, val) {
// Format the text to display.
var str = val.ProductDescription + ': $' + val.MSRP;
$('#products').html(str);
});
})
.fail(
function (jqXHR, textStatus, err) {
$('#products').html('Error: ' + err);
});
}
All Products
ID:
我遇到的问题是与查找()函数将呈现的UI有意义的数据,我看到那个数据匹配ID 12345已成功返回。
谢谢。
+0
在每个语句前添加一个调试器并检查json对象格式 –
2012-07-06 20:06:50
+0
我猜你的web方法在指定一个id时返回单个对象[不是数组],你能告诉你代码 –
2012-07-06 20:08:52
+0
不,我的web方法有一个填充List的GetAll,当我试图获得一个特定的产品时,我可以看到一个产品在我的调试器中返回。 –
2012-07-06 20:14:28