繁体   English   中英

如何使用 jquery 在 MVC 中制作可编辑表?

[英]How to make an editable table in MVC using jquery?

我正在使用“数据库优先”方法构建我的第一个 MVC 应用程序,一切正常,但是,我坚持使用 jQuery 使 MVC 表可编辑(内联),当我点击它时,每一行都有一个链接链接,场景应该如下:-

1 单击特定行中的链接
2-让这个特定的行可编辑

问题如下:-
1-当我点击特定行的链接时
2-所有行都可以编辑了!!!

这是 HTML 代码:-

<table id="my_table">
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.AFECode)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Remarks)
                </th>
                <th></th>
            </tr>

            @foreach (var item in Model)
            {
                <tr contenteditable="false">
                    <td contenteditable="false">
                        @Html.DisplayFor(modelItem => item.AFECode)
                    </td>
                    <td contenteditable="false">
                        @Html.DisplayFor(modelItem => item.Remarks)
                    </td>
                    <td contenteditable="false">
                        <a id="edit_link" href="#" onclick="edit()" >edit</a>
            }

        </table>

这是包含edit()函数的 Jquery 代码:-

function edit() {
    $("#my_table td").attr("ContentEditable") == "false" ? $("#my_table td").attr("ContentEditable", "true") : $("#my_table td").attr("ContentEditable", "false")
}

现在,我怎样才能只得到我点击的链接的那一行是可编辑的?
提前致谢

您的$("#my_table td")选择器选择所有<td>元素,因此切换所有表格单元格的contenteditable状态。 由于每个<a>元素中的重复id属性,您还会生成无效的 html。

避免使用行为污染您的标记并使用Unobtrusive Javascript ,并使用相对选择器来获取与链接关联的<td>元素

<a class="edit" href="#">edit</a> <!-- use a class name-->
$('.edit').click(function() {
    // to get the associated row
    var row = $(this).closest('tr');
    // or to get the associated cells
    var cells = $(this).closest('tr').children('td');
    // or just the sibling cells
    var siblings = $(this).closest('td').siblings('td');
});

最初没有理由添加contenteditable ,您可能希望向用户提供反馈,以便他们知道他们正在编辑哪一行,例如,您的代码可能是

@foreach (var item in Model)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => item.AFECode)</td>
        <td>@Html.DisplayFor(modelItem => item.Remarks)</td>
        <td><a class="edit" href="#">edit</a></td>
    </tr>
}

$('.edit').click(function () {
    var row = $(this).closest('tr');
    row.toggleClass('isediting'); // add a style to highlight the row
    var isediting = row.hasClass('isediting');
    $(this).parent('td').siblings('td').prop('contenteditable', isediting);
    if (isediting) {
        $(this).text('update');
    } else {
        $(this).text('edit');
    }
})

但是请注意,这不是编辑模型的方法。 要么为for循环中的所有元素生成表单控件,要么在表单中使用EditorTemplate并提交到控制器方法(请参阅此示例)或使用包含集合中一个项目的表单的 jquery 对话框,并在单击“编辑”时按钮,将行数据传输到表单控件并使用ajax保存数据,如果成功,更新行中的值。

暂无
暂无

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

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