1. Идентификатор элемента html должен быть уникальным, поэтому вы можете добавить class="ProductId"
к каждой строке столбца Products
и изменить jquery, как показано ниже:
<td class="ProductId" name="ProductId">@item.ProductId</td>
<script>
function GetProductName(id,index) {
$.get('/OrderLine/GetProductNameById?ProductId=' + id, function (data) {
}).always(function (result) {
$(index).html(result);
});
}
$('.ProductId').each(function(i, obj) {
var MyVal = $(this).html();
console.log(MyVal);
GetProductName(MyVal,this);
});
</script>
2. Лучше, кажется, что отношение между orderLine и Product является взаимно-однозначным, вы можете обратиться к следующей модели и использовать Include()
чтобы загрузить соответствующие данные о продукте, чтобы получить ProductName непосредственно в представлении:
OrderLine
public class OrderLine
{
public int Id { get; set; }
public int Price { get; set; }
public int Count { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
}
Контроллер
public IActionResult OrderList()
{
var model = _context.OrderLine.Include(o=>o.Product).ToList();
return View(model);
}
Просмотр
<table class="table table-bordered table-striped">
<tr>
<th>Count</th>
<th>Price</th>
<th>Products</th>
<th>Detail</th>
</tr>
@foreach (var item in Model)
{
<tr id="Mytr">
<td>@item.Count</td>
<td>@item.Price</td>
<td class="ProductId" name="ProductId">@item.Product.Name</td>
<td><a asp-controller="OderLine" asp-action="Index" asp-route-id="@item.Id">Detail</a></td>
</tr>
}
</table>