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

时间:2020-08-26 10:59:42

标签: javascript asp.net asp.net-core asp.net-core-mvc dynamic-list

我正在尝试从列表中删除或隐藏项目,而我面临两个问题,1-新近无法删除,2-尝试使用Javascript将已删除项目标记为isDeleted = true,然后在中删除它们遵循此答案https://stackoverflow.com/a/40572625/10773318的控制器,但是它不起作用。

这是我的视图模型

 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 个答案:

答案 0 :(得分:2)

1-新近无法删除

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

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

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

2-尝试使用Javascript将删除的项目标记为isDeleted = true

要达到此要求,您可以参考以下代码段。

<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>

测试结果

enter image description here

相关问题