我在使用 ajax 重新加载部分 View 时遇到一个有趣的问题。我在主视图中有以下设置:
<div>
<div id="items">
@Html.Partial("SubView", Model.Items);
</div>
<div>
subview 通常是表格中的项目列表,如下所示:
<table class="table table-striped">
<tr>
<th>Date</th>
<th>Time</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
@Html.HiddenFor(modelItem => item.Id)
<td>@Html.DisplayFor(modelItem => item.Date)</td>
<td>@Html.DisplayFor(modelItem => item.Time)</td>
<td>
@Html.ActionLink("Delete", "Delete", new { itemId= item.Id, page = Model.PageNumber }, new { @class = "deleteItem" })
</td>
</tr>
}
Controller 中的DeleteItem Action 基本上执行以下操作:
[HttpDelete]
public ActionResult DeleteItem(int itemId, int page)
{
this.dbService.DeletItem(expenseId);
return PartialView("SubView", this.GetPagedList(page));
}
在我在主视图中引用的脚本中,我有以下代码:
$(document).ready(function () {
// delete expense
$(".deleteItem").click(function () {
$.ajax({
url: this.href,
type: 'delete',
success: function (result) {
$("#items").html(result);
}
});
return false;
});
第一次工作正常,但第二次它只加载部分 View -> 因为 JavaScript 代码没有被执行...
我对这些东西比较陌生,我有点困惑这里发生了什么。 所有第 3 方脚本均在 Layout.cshtml 中呈现
最佳答案
您无法将 .click()
事件附加到动态生成的项目。你必须这样构建它:
$(document).on('click', '.deleteItem', function() {
// Deletey stuff here.
});
关于javascript - 重新加载部分 View 和 Ajax - ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39085101/