繁体   English   中英

重新加载部分视图和Ajax-ASP.NET MVC

[英]Reloading partial views and Ajax - ASP.NET MVC

在用ajax重新加载部分视图时遇到一个有趣的问题。 我在主视图中有以下设置:

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

控制器中的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.
});

要渲染部分视图,必须将返回类型设置为PartialViewResult而不是ActionResult。 因为ActionResult导致重定向。

尝试像这样编辑DeleteItem函数。

[HttpDelete]
    public PartialViewResult DeleteItem(int itemId, int page)
    {
        this.dbService.DeletItem(expenseId);
        return PartialView("SubView", this.GetPagedList(page));
    }

暂无
暂无

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

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