javascript - 从动态列表中删除项目 ASP Core MVC
问题描述
我正在尝试从列表中删除或隐藏项目,我面临两个问题,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-新的不能删除
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>
测试结果
推荐阅读
- python - 如何在不违反 PEP-8 的情况下从另一个目录导入文件?
- php - php过滤数组
- java - DL4J 使用 Apache Spark 在 GPU 上运行(非训练)LSTM 神经网络?
- android - 从 Fragment 获取 viewPager 参考
- html - Tibco Spotfire。如何与锚点超链接
- python - AttributeError:模块“cv2.cv2”没有属性“CV_LOAD_IMAGE_COLOR”
- html5-canvas - 带有子路径的 HTML5 Canvas 非零填充规则
- selenium - 如果我们在锁定的机器上运行测试,Selenium Microsoft Edge 浏览器自动化会停止并失败
- angular - E2E Angular 6 websocket 模拟
- android - 使用 Flutter 接收共享文件意图