通过 AJAX Get 填充显示迭代表

Populating display iteration table through AJAX Get

本文关键字:迭代 显示 填充 AJAX Get 通过      更新时间:2023-09-26

有一个视图表,当用户选择特定日期时,该表显示模型类型列表的静态元素,或者在模型为空时不显示任何内容。 我以前更改过单个唯一字段的值,但从未更改过模型列表的字段。 在搜索 SO 时,我没有找到解决这种情况的问题,但一些相关问题建议使用序列化。 我尝试引用列表名称并将其填充/设置为等于返回的数据,但无济于事。 此外,通过 ActionResult 没有错误,因此问题可能出在 AJAX 将返回值分配给列表字段。 有什么办法可以做到这一点吗?

.HTML:

<div class="row">
    <div class="col-lg-8">
        @Html.LabelFor(m => m.PriceDate, "Pricing Date")
        @Html.DropDownListFor(m => m.PriceDate, Model.PricingDates, "--New Pricing--")
    </div>
</div>
<div class="row">
<table id="dt_terms" class="table table-striped">
    <tbody>
        <tr><th></th><th class="text-center">ID</th><th class="text-center">Price</th><th class="text-center">Adder Fee</th></tr>
        @if (Model.Prices.Any()) //NEEDS POPULATING!
        {
            for (var i = 0; i < 100; i++)
            {
                <tr>
                    <td><input type="submit" class="btn btn-info" id="priceToOffer" value="Add To Offers"></td>
                    <td class="text-center">@Html.DisplayFor(m => m.Prices[i].ID)</td>
                    <td class="text-center">@Html.TextBoxFor(m => m.Prices[i].Price, new { @class = "form-control", data_parsley_required = "true" })</td>
                    <td class="text-center">@Html.DisplayFor(m => m.Prices[i].AdderFee)</td>
                </tr>
            }
        }
    </tbody>
</table>

脚本:

$(function () {
    $("#PriceDate").change(function () {
        var $priceTable = $("#dt_terms"),
            $priceValue = $("#PriceDate").val(),
            $pID = { iD: $priceValue };
        if ($(this).val()) {
            //make AJAX call for historical Price data and populate table
            $.ajax({
                type: "GET",
                url: '@Url.Action("GetPrices", "Sales")',
                data: $pID,
                success: function (data) {
                    //Fill data
                    $("#Prices").val(data);
                }
            });
            $priceTable.prop("disabled", true);
        }
        else {
            //clear data
            $("#Prices").val('');
            $priceTable.prop("disabled", false);
        }
    }).change();
});

控制器:

public ActionResult GetPrices(string iD)
{
    int priceID;
    Int32.TryParse(iD, out priceID);
    //priceID = iD;
    dbEntities db = new dbEntities();
    var selectedPrice = new List<PricesModel>();
    var accountPrices = db.uspGetPrices(priceID);
    foreach (var result in accountPrices)
    {
        var price = new PricesModel
        {
            ID = result.PriceID,
            Price = result.Price,
            AdderFee = result.AdderFee,
        };
        selectedPrice.Add(price);
    }
    return Json(selectedPrice, JsonRequestBehavior.AllowGet);
}

生成的 HTML:

<div class="row">
    <div class="col-lg-8">
        <label for="PriceDate">Pricing Date</label>
        <select data-val="true" data-val-number="The field PriceDate must be a number." data-val-required="The PriceDate field is required." id="PriceDate" name="PriceDate"><option value="">--New Pricing--</option>
<option value="2">1/4/2016 6:33 PM</option>
</select>
    </div>
</div>
<div class="row">
    <table id="dt_terms" class="table table-striped">
        <tbody>
            <tr><th></th><th class="text-center">ID</th><th class="text-center">Price</th><th class="text-center">Adder Fee</th></tr>
        </tbody>
    </table>
</div>

这是服务器端代码:

@if (Model.Prices.Any()) //NEEDS POPULATING!

当页面在客户端上呈现时,该代码早已完成,不再执行。 在 AJAX 响应处理程序中,需要使用新数据填充客户端标记。

这些数据是什么? 它是表的全新数据集吗? 在这种情况下,您可能只是从表中删除行并添加新行。 像这样:

success: function (data) {
    $('#dt_terms tbody tr').remove();
    for (var i = 0; i < data.length; i++) {
        var row = $('<tr></tr>');
        var idCell = $('<td></td>').append($('<input type="submit" class="btn btn-info" id="priceToOffer" value="Add To Offers">'));
        row.append(idCell);
        // continue for other cells in the table
        $('#dt_terms tbody').append(row);
    }
}

这个想法是,您将使用新数据重新构建标记,类似于最初由服务器端代码构建它的方式。

<小时 />

您可能会注意到,这会将一些标记结构复制到 jQuery 代码中。 随着系统变得越来越复杂并且这种情况不断发生,您可能需要研究客户端框架,例如 AngularJS,它允许您定义视图并将模型绑定到它们,类似于服务器端代码。

在这样的情况下,你基本上是在做一些与你最初尝试的事情非常相似的事情:

$("#Prices").val(data);

语法当然会有所不同,并且正在执行的操作的基本原理也会有所不同(更新内存中的对象而不是 DOM 元素的值),但从语义上讲,它似乎更直观地了解您最初想要如何处理这个问题。 它将更新视图绑定到的对象,结果视图将自动更新。

在客户端代码中没有这样的 MVC 或 MVVM 框架的情况下,您只需使用 jQuery 手动更新表。 在这样的小情况下,这并不可怕。