我有 js DataTable 来显示项目列表。 每个项目的属性和图像都很少。 我创建 js DataTable 来显示所有信息。 除了图像之外,一切正常。 通常图像可以通过链接访问:
@product.ProductImages.ImageUrl
我的js数据表代码:
function loadDataTable() {
dataTable = $('#tblData').DataTable({
"ajax": { url: '/admin/product/GetAll' },
"columns": [
{ data: 'name', "width": "15%" },
{ data: 'category.name', "width": "10%" },
{
data: 'imageUrl', "render": function (data, type, row) {
return '<img src="' data.product.ProductImages.FirstOrDefault().ImageUrl + '" "/>';
}, "width": "10%"
},
{ data: 'description', "width": "30%" },
{ data: 'price', "width": "5%" },
}
]
图像未显示在数据表中。 我尝试使用
<img src="' + data.ProductImages.FirstOrDefault().ImageUrl + '"
或者只是
<img src="' + data + '">
但是没有任何效果.. 我在项目控制器中有代码来显示图像,并且在调试步骤中它确实显示,每个项目都有 N 个图像..我只想在表中显示 1 个图像..
我做错了什么? 谢谢你。
但是没有任何作用..我确实在项目控制器中有代码要显示 图像,并且在调试步骤中确实显示,每个项目有 N 图片数量..我只想在表格中显示 1 张图片..
我做错了什么?
根据您的场景和描述,您的
data.product.ProductImages.FirstOrDefault().ImageUrl
查询似乎可能存在问题。确保它返回您绑定到 image src
的单个且正确的图像网址
由于您尚未分享此详细信息,因此我无法对其进行测试。除此之外,我还研究了演示图像 url 和其余代码及其按预期工作。
以下是我调查您的情况的步骤:
演示模型:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
}
演示控制器:
[HttpGet]
public IEnumerable<Product> Get()
{
return new List<Product>
{
new Product { Id = 1, Name = "Product 1", ImageUrl = "https://ip.keycdn.com/example.jpg?width=70&quality=10" },
new Product { Id = 2, Name = "Product 2", ImageUrl = "https://ip.keycdn.com/example.jpg?width=70&quality=10" },
};
}
查看:
<table id="productTable" class="display">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Image</th>
</tr>
</thead>
<tbody></tbody>
</table>
@section scripts {
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.6/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'https://localhost:7163/products/Get',
success: function (response) {
console.log(response);
$('#productTable').DataTable({
data: response,
columns: [
{ data: 'id' },
{ data: 'name' },
{
data: 'imageUrl',
render: function (data, type, row) {
return '<img src="' + data + '" alt="' + row.name + '" height="50">';
}
}
]
});
},
error: function (response) {
alert(response.responseText);
}
});
});
</script>
}
输出: