Как я могу изменить идентификатор в виде сетки на значение? - PullRequest
0 голосов
/ 07 января 2020

Как я могу изменить идентификатор в виде сетки на значение? Этот код ниже работает только для первой записи. Как я могу запустить его для всех записей?

Код моего действия:

public JsonResult GetProductNameById(int ProductId)
{
    var productname = producteRepository.GetAll().Where(c => c.Id == ProductId).FirstOrDefault();
    return Json(productname.Name);
}

Сетка:

enter image description here

Код моего просмотра :

@model List<ItcNetworkMarketing.Domain.Core.orderLine>

@if (Model != null && Model.Count > 0)
{
    <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 id="ProductId" name="ProductId"  >@item.ProductId</td>
                <td><a asp-controller="OderLine" asp-action="Index" asp-route-id="@item.Id">Detail</a></td>

            </tr>
        }

    </table>
}
<script src="~/scripts/jquery-3.4.1.js"></script>

<script>
   
    function GetProductName(id) {

        $.get('/OrderLine/GetProductNameById?ProductId=' + id, function (data) { 
                }).always(function(result) {
                    $("#ProductId").html(result);
                });
    
        }



    $("#ProductId").add(function () {

        var MyVal = $("#ProductId").html();
        console.log(MyVal);
        GetProductName(MyVal);

    });


</script>

1 Ответ

1 голос
/ 08 января 2020

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...