删除子项后,MVC4重定向到父项

时间:2013-05-07 14:04:11

标签: c# asp.net-mvc

我有删除项目的删除操作。删除此项后,我想重定向到已删除项目的父项的操作。

    // The parent Action
    public ActionResult ParentAction(int id = 0)
    {
        Parent parent = LoadParentFromDB(id);
        return View(parent);
    }

    // Delete action of the child item
    public ActionResult Delete(int id, FormCollection collection)
    {
        DeleteChildFromDB(id);
        return RedirectToParentAction();
    }

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:7)

使用RedirectToAction方法并传递父对象的ID

// Delete action of the child item
public ActionResult Delete(int id, FormCollection collection)
{
    var parent_id = queryTheParentObjectId();
    DeleteChildFromDB(id);
    return RedirectToAction("ParentAction", new {id=parent_id})
}

您创建了自己的答案,似乎您要调用的方法是在另一个控制器中。您不需要将控制器名称添加为参数。你可以这样:

// instead of doing this
// return RedirectToAction("ParentAction", 
//    new { controller = "ParentController", id = parent_id });
//
// you can do the following
// assuming ParentConroller is the name of your controller
// based on your own answer 
return RedirectToAction("ParentAction", "Parent", new {id=parent_id})

答案 1 :(得分:0)

谢谢@von v。 我已经修改了你的答案并且它有效:

// Delete action of the child item
public ActionResult Delete(int id, FormCollection collection)
{
    var parent_id = queryTheParentObjectId();
    DeleteChildFromDB(id);
    return RedirectToAction("ParentAction", new { controller = "ParentController", id = parent_id });
}