简体   繁体   English

如何在Ajax中传递每个行表的值

[英]How to pass value of each row table in Ajax

I have page where it displays a list of orders. 我在页面上显示订单列表。 I'm trying pass the value of each row of the table when a user clicks on a button, but it always passes a null value to my controller & database. 我试图在用户单击按钮时传递表中每一行的值,但是它总是将空值传递给我的控制器和数据库。 Can anyone please help me or point me in to the right direction? 任何人都可以帮助我或为我指出正确的方向吗? Thanks in advance. 提前致谢。

This is my code: 这是我的代码:

The view, 风景,

<table class="table">
    <tbody>
    @foreach (var item in Model)
    {
    <tr>
        <td>
            <div class="product-title">
                <a href="/Main/Produktdetaljer/@item.ProductId?proid=@item.ProductId">
                    @Html.DisplayFor(modelItem => item.ProductName)
                    <input type="hidden" name="item_name" class="item_name" value="@item.ProductName">
                </a>
            </div>
        </td>
        <td>
            <ul>
                <li>
                    <div class="base-price price-box"> 
                        <span class="price"> 
                            @Html.DisplayFor(modelItem => item.Price) 
                            <input type="hidden"  class="price" value="@item.Price">
                        </span> 
                    </div>
                </li>
            </ul>
        </td>
        <td class="QuantityOfProduct@(item.ProductId)">
            @Html.DisplayFor(modelItem => item.Quantity)
            <input type="hidden" class="quantity" value="@item.Quantity" />
        </td>
    </tr>
    }
    </tbody>
</table>
<div class="col-sm-6">
    <div><a class="sendordre" >Send</a></div>
</div>

The javascript, javascript

$(".sendordre").click(function (e) {
    e.preventDefault();
    $('tr').each(function (i, el) {
        var ProductName = $(el).children('td').children('.item_name').val();
        var Qty = $(el).children('td').children('.quantity').val();
        var Price = $(el).children('td').children('.price').val();

        $.ajax({
            type: 'POST',
            url: "@Url.Action("SendOrdre", "Cart")",
            dataType: 'json',
            data:{ 
                   ProductName: ProductName,
                   Price: Price,
                   Qty: Qty,
                   send:"send"
            },
            success: function (run) {
                if (run) {
                    console.log("Ok");
                }
                else {
                    console.log("ERror");
                }
            },
        });
    });
});

The controller method, 控制器方法

public JsonResult SendOrdre(CustomerOrdersVM model) {

    DateTime CreatedAt = DateTime.Today;
    var SaveOrdrer = new CustomerOrders  {

        Qty = model.Qty
        ProductName = model.ProductName,
        Price = model.Price,
        CreatedAt = CreatedAt,
    };

    db.CustomerOrders.Add(SaveOrdrer);
    db.SaveChanges();

    return Json(model, JsonRequestBehavior.AllowGet);

}

You should replace 你应该更换

$(el).children('td').children

with simply 简单地

$(el).find

.children() only goes one layer down in the DOM, but your item name and quantity fields are actually several layers down inside the tds...so probably it's simply not finding the values in the page. .children()在DOM中仅下降了一层,但您的商品名称和数量字段实际上在tds内部下降了几层...因此,很可能是在页面中找不到值。 .find() is more flexible and will keep on searching down until it hits the selector. .find()更加灵活,并且会一直向下搜索,直到命中选择器为止。 So it's far less dependent on the precise structure of your HTML. 因此,它几乎不再依赖于HTML的精确结构。

You also need to change <span class="price"> to something else - this duplicates the "price" class of your hidden field, and confuses jQuery about which element you're trying to find. 您还需要将<span class="price">更改为其他内容-这将复制隐藏字段的“ price”类,并使jQuery混淆您要查找的元素。 Since the span is first, it finds that first, but spans don't have a "value", so running .val() on it returns nothing. 由于范围是第一个,因此它首先找到它,但是范围没有“值”,因此在其上运行.val()不会返回任何内容。

Lastly it would be sensible to restrict the loop just to finding rows within the orders table, otherwise it may operate on rows in other tables in your page, which is not desirable. 最后,将循环限制为仅在orders表中查找行将是明智的,否则可能会对页面中其他表中的行进行操作,这是不希望的。 For that purpose I've added an id="ordersTable" attribute to the table, and then changed the selector from $("tr") to $("#ordersTable tr") so it selects rows only within the intended table. 为此,我在表中添加了id="ordersTable"属性,然后将选择器从$("tr")更改$("#ordersTable tr")以便仅在预期表中选择行。

Docs: https://api.jquery.com/children/ and https://api.jquery.com/find/ 文件: https//api.jquery.com/children/https://api.jquery.com/find/

Here's a static demo (I created two rows, and replaced the Razor code with dummy output, and the ajax request with a log of the data to be sent): 这是一个静态演示(我创建了两行,并用虚拟输出替换了Razor代码,并将ajax请求替换为要发送的数据的日志):

 $(function() { $(".sendordre").click(function(e) { e.preventDefault(); $("#ordersTable tr").each(function(i, el) { var ProductName = $(el).find('.item_name').val(); var Qty = $(el).find('.quantity').val(); var Price = $(el).find('.price').val(); /*$.ajax({ type: 'POST', url: "@Url.Action(" SendOrdre ", " Cart ")", dataType: 'json', data: { ProductName: ProductName, Price: Price, Qty: Qty, send: "send" }, success: function(run) { if (run) { console.log("Ok"); } else { console.log("ERror"); } }, });*/ //dummy test code console.log({ ProductName: ProductName, Price: Price, Qty: Qty, send: "send" }); }); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="ordersTable" class="table"> <tbody> <tr> <td> <div class="product-title"> <a href="/Main/Produktdetaljer/1?proid=1"> Product1 <input type="hidden" name="item_name" class="item_name" value="Product1"> </a> </div> </td> <td> <ul> <li> <div class="base-price price-box"> <span class="priceSpan"> 100 <input type="hidden" class="price" value="100"></span> </div> </li> </ul> </td> <td class="QuantityOfProduct1"> 10 <input type="hidden" class="quantity" value="10" /> </td> </tr> <tr> <td> <div class="product-title"> <a href="/Main/Produktdetaljer/2?proid=2"> Product2 <input type="hidden" name="item_name" class="item_name" value="Product2"> </a> </div> </td> <td> <ul> <li> <div class="base-price price-box"> <span class="priceSpan"> 200 <input type="hidden" class="price" value="200"></span> </div> </li> </ul> </td> <td class="QuantityOfProduct2"> 20 <input type="hidden" class="quantity" value="20" /> </td> </tr> </tbody> </table> <div class="col-sm-6"> <div> <a class="sendordre">Send</a> </div> </div> 

Change val() to text() : val()更改为text()

var ProductName = $(el).children('td').children('.item_name').text();
var Qty = $(el).children('td').children('.quantity').text();
var Price = $(el).children('td').children('.price').text();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM