MVC3 & Ajax :刷新列表以隐藏通过单击按钮从列表中删除的记录

MVC3 & Ajax : Refresh list to hide a record which was deleted from list by a button click

我有一个列表,显示已订阅的论坛主题,每一行都有一个取消订阅按钮。我使用 Ajax 取消订阅工作正常,但我想使用 Ajax 刷新以从列表中删除未订阅的线程。谁能建议我。我的代码如下:

使用 Ajax 的想法是因为我只想刷新列表部分而不是整个页面。

Index.aspx

<% foreach (var thread in Model.threads) { %>
    <tr>
        <td><%: thread.Title %></td>
        <td><%: Ajax.ActionLink("Unsubscribe", "ToggleForumAlertFromList",
                    new { id = thread.ForumId },
                    new AjaxOptions { HttpMethod = "POST", 
                        UpdateTargetId = "none", 
                    new { ID = "togglealertlink" })%>
        </td> 
    </tr>
<% } %>       

控制器

[HttpPost]
public ActionResult ToggleThreadAlertFromList(Guid id)
{
    // Do stuff to unsubscribe        
    return new EmptyResult();
}

您需要连接在 POST 完成时触发的 OnSuccess 回调。

此回调可以重新查询您的列表或只是从您的列表中删除未订阅的项目。

<% foreach (var thread in Model.threads) { %>
    <tr id= "<%: thread.ForumId %>">
        <td><%: thread.Title %></td>
        <td><%: Ajax.ActionLink("Unsubscribe", "ToggleForumAlertFromList",
                    new { id = thread.ForumId },
                    new AjaxOptions { HttpMethod = "POST", 
                        UpdateTargetId = "none", 
                        OnSuccess = "removeItem('thread.ForumId')"
                    new { ID = "togglealertlink" })%>
        </td> 
    </tr>
<% } %> 

function removeItem(itemId) {
    $("#" + itemId).remove();
}

这假设每个父 <tr> 元素都被分配了一个唯一的 forumId,如上所示。