首页 > 解决方案 > 如何在 Asp.Net Core 中动态更新表的每一行

问题描述

我正在使用 Asp.Net Core(Razor Pages) 开发一个 Web 应用程序,我有一个包含三列的表格,一列代表手机号码,另一列应该发送给每个人的文本消息,最后一个显示结果。我正在寻找一种方法来更新每一行的最后一列,并通过单击表格下方的“全部发送”按钮将每条消息发送到手机号码时突出显示它。我该如何完成?提前感谢您的回复。

    <div class="row mt-2">
        <table class="table table-striped table-responsive-md">
            <thead class="thead-dark">
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.MessageList[0].ReceiverCellPhone)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.MessageList[0].Text)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.MessageList[0].Result)
                    </th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model.MessageList)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.ReceiverCellPhone)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Text)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Result)
                        </td>
                        <td></td>
                    </tr>
                }
            </tbody>
        </table>
    <button type=submit value=Send to All/>
    </div>

标签: c#asp.net-corerazor-pages

解决方案


我认为在这样的场景中,我们希望通过 javascript 而不是通过 html 属性将事件附加到操作,从而使我们的 javascript 尽可能不引人注目。

有了它,您可能需要以下内容:

document.getElementById('ButtonId').addEventListener('click', function() {
    // you are now in the button click context

    // you can now either fire one asyncronous request which encapsulates all the 
       rows or you can iterate through the table rows and fire individual requests. The below shows the second example

    var table = document.getElementById('TableId');
    var url = "url to endpoint you want to call';

    for (var i = 1; i < table.rows.length; i++) { // 1 so we miss the header
         // get the relevant id of the request you want to send
         var id = "whatever cell you need";
         let request = new XMLHttpRequest();
         request.onreadystatechange = function () {
             if (this.readyState === 4) {
                 //success so you can change the cell you want to change
             } else {
                 document.body.className = 'error';
             }
         }
         request.open("post", url, true);
         request.send('this should be whatever you want to send to the request - id object maybe");
     }
 });

如果您想将该函数作为适当的函数或变量,那么您也可以轻松地做到这一点,以使代码更易于阅读


推荐阅读