データベースから返された製品リストから特定の製品を検索し、この製品をhtmlページに表示するためのIDを取得する単純なページがあります。/ 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ページです
<html lang="en">
<head>
<title>.:: Web API ::.</title>
<script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(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.
$('<li/>', { 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);
});
}
</script>
</head>
<body>
<div>
<h1>All Products</h1>
<ul id='products' />
</div>
<div>
<label for="prodId">ID:</label>
<input type="text" id="prodId" size="5"/>
<input type="button" value="Search" onclick="find();" />
<p id="product" />
</div>
私が抱えている問題は、UIに意味のあるデータをレンダリングするfind()関数にあり、ID12345に一致するデータが正常に返されることがわかります。
ありがとう。