MVC:我从网格中删除了一行,但我的页面没有刷新

时间:2011-02-04 17:22:18

标签: asp.net-mvc

我有一个Html.Helper用于删除网格中的行。 它在我的控制器上调用以下方法;

   [AcceptVerbs(HttpVerbs.Delete)]
    public ActionResult Delete(int _employeeOtherLeaveId)
    {
        EmployeeOtherLeaf.Delete(_employeeOtherLeaveId);
        return RedirectToAction("Payroll");
    }

这会在我的控制器上调用GET方法,我希望刷新网格视图,但事实并非如此。当我手动刷新时,我看到该行实际上已被删除。这是为什么?

[HttpGet]
public ActionResult Payroll()
{
    if ((SessionObjects.PeriodStartDate > DateTime.MinValue) && (SessionObjects.PeriodEndDate > DateTime.MinValue))
        if (SessionObjects.PayrollSelectedEmployeeId == 0)
            return View(new PayrollViewModel()
                {
                    PeriodStartDate = SessionObjects.PeriodStartDate,
                    PeriodEndDate = SessionObjects.PeriodEndDate
                });
        else
            return View(new PayrollViewModel(
                SessionObjects.PeriodStartDate,
                SessionObjects.PeriodEndDate,
                SessionObjects.PayrollSelectedEmployeeId
                ));

    return View();
}

1 个答案:

答案 0 :(得分:3)

这取决于您如何调用DELETE操作。从您的previous questionanswer you accepted判断,我认为您正在执行以下操作:

onclick="$.ajax({url: this.href, type: 'DELETE'}); return false;"

这显然是不够的,因为您发送AJAX请求要删除但是您没有处理success事件来更新DOM。所以你可能需要这样做:

$.ajax({
    url: this.href, 
    type: 'DELETE',
    success: function(result) {
        // update some DOM element with the result returned by the
        // server. So supposing that you have some <div id="someContainer">
        // that will contain the part of the DOM you want updated:
        $('#someContainer').html(result);
    }
}); 
return false;

现在很明显,当你使用自定义帮助程序时,将所有这些javascript填充到HTML中是很难看的。我个人会使用不引人注目的JavaScript。我希望我的助手用类生成一个普通的锚,然后在一个完全独立的javascript文件中我会AJAX化这个链接:

$(function() {
    // AJAXify the anchor with the delete class that would
    // be generated by your custom helper
    $('.delete').click(function() {
        $.ajax({
            url: this.href, 
            type: 'DELETE',
            success: function(result) {
                // update some DOM element with the result returned by the
                // server. So supposing that you have some <div id="someContainer">
                // that will contain the part of the DOM you want updated:
                $('#someContainer').html(result);
            }
        }); 
        return false;
    });
});