从动态列表中删除项目 ASP Core MVC

Deleting items from dynamic list ASP Core MVC

我正在尝试从列表中删除或隐藏项目,但我遇到了两个问题,1- 无法删除新项目,2- 尝试使用 [=26= 将已删除的项目标记为 isDeleted = true ] 然后稍后在控制器中按照此答案删除它们 但它没有用。

这是我的视图模型

 public class CreateEditParentViewModel
{
    public int Id { get; set; }
    public IList<ChildViewModel> ChildrenLists { get; set; }
}

    public class ChildViewModel
{
        public int Id { get; set; }
        public string Name { get; set; }
        public bool isDeleted { get; set; } 
}

在主视图中

    <div id="editorRows">
    @foreach (var item in Model.ChildrenLists)
    {
        <partial name="_RowPartial" model="item" />
    }
    </div>
<a id="addItem" asp-action="BlankRow" asp-controller="Home">Add Row...</a> <br />
<input type="submit" value="Finished" />

主视图中的javascript

@section scripts {
<script>
    $("#addItem").click(function () {
        $.ajax({
            url: this.href,
            cache: false,
            success: function (html) { $("#editorRows").append(html); }
        });
        return false;
    });

    $("a.deleteRow").click(function () {
        $(this).parents("div.editorRow:first").remove(); //does not work with newly added
        return false;
    }); //what it should do: hide and set isDeleted = true if id is not null - remove if null
</script>

最后是局部视图

<div class="editorRow">
@using (Html.BeginCollectionItem("ChildrenLists"))
{
    @Html.HiddenFor(m => m.Id)
    @Html.HiddenFor(m => m.isDeleted)
    <span>Name: </span> @Html.EditorFor(m => m.Name);
}
<a href="#" class="deleteRow">delete</a>

1- the newly cannot be removed

您可以为新生成的 <a href="#" class="deleteRow"> 元素手动绑定 click 事件处理程序,如下所示。

success: function (html) {
    $("#editorRows").append(html);

    $("a.deleteRow").bind("click", function () {
        //...
        //code logic here
    });
}

2- Tried to tag the deleted items as isDeleted = true using Javascript

实现需求,可以参考下面的代码片段。

<script>
    $("#addItem").click(function () {
        $.ajax({
            url: this.href,
            cache: false,
            success: function (html) {
                $("#editorRows").append(html);

                $("a.deleteRow").bind("click", function () {
                    del_row($(this));
                });
            }
        });
        return false;
    });

    $("a.deleteRow").click(function () {

        del_row($(this));
           
        return false;
    }); 

    function del_row(el) {
        console.log("del");
        console.log($(el).siblings("input[id$='__Id']").val());
        var childitem_id = $(el).siblings("input[id$='__Id']").val();

        if (childitem_id == 0 || childitem_id == "") {
            $(el).parent("div.editorRow").remove();  
        } else {
            $(el).siblings("input[id$='__isDeleted']").val("true");
            $(el).parent("div.editorRow").hide();
        }

        return false;
    }
</script>

测试结果