我有一个MVC5应用程序,它有几个控制器,脚手架上有EF6 CRUD操作和相关视图。这些控制器/视图集之一用于管理病人标识符表,并且在编辑或删除完成后,控制器按预期返回到标识符索引视图的操作链接。
但是,患者标识符也显示在患者控制器的各种视图上,并且从Patient.Edit视图中,我对标识符控制器的编辑或删除操作进行了Html.ActionLink调用。当从Patient.Edit视图调用后者时,我希望它们在完成时返回到该视图。
我有什么办法能做到这一点吗?
发布于 2014-08-22 15:54:15
是的,但这始终是一个手工过程。MVC中没有专门为返回URL构建的内容。
本质上,您的编辑/删除链接将需要包含一个GET param,通常称为returnUrl,尽管名称并不重要,它将被设置为当前的页面URL。例如:
@Html.ActionLink("Edit", new { id = patient.Id, returnUrl = Request.RawUrl })然后,您的编辑/删除GET操作应该接受这个参数,并设置一个ViewBag成员:
public ActionResult Edit(int id, string returnUrl = null)
{
    ViewBag.ReturnUrl = returnUrl;
    return View();
}在编辑表单中,添加一个隐藏字段:
@Html.Hidden("returnUrl", ViewBag.ReturnUrl)在发布编辑操作中,再次接受param:
[HttpPost]
public ActionResult Edit(int id, Patient model, string returnUrl = null)但在这个行动中,你现在会做一些不同的事情。通常情况下,当您获得一个成功的帖子并保存了对象或其他什么时,您会执行如下操作:
return RedirectToAction("Index");但是,现在应该检查returnUrl是否有值,如果有,则重定向到该值:
if (!string.IsNullOrEmpty(returnUrl))
{
    return Redirect(returnUrl);
}
return RedirectToAction("Index");MVC5 with Identity示例项目有一个很好的助手方法,它使用:
private ActionResult RedirectToLocal(string returnUrl)
{
    if (Url.IsLocalUrl(returnUrl))
    {
        return Redirect(returnUrl);
    }
    else
    {
        return RedirectToAction("Index", "Home");
    }
 }这将进入您的控制器,基本上与我已经描述过的有两个显著不同之处的操作相同:
Url.IsLocalUrl来检查返回url实际上是这个站点上的一个URL。这是一个智能检查,因为它最初是在URL的查询字符串中传递的,因此可以由用户操作。RedirectToLocal(returnUrl),如果有一个返回URL集,它将被使用。否则,将使用回退重定向。发布于 2014-08-22 15:54:24
在我的一个项目中,我就是这样做的:
public ActionResult Edit(int id, string returnUrl)
{
    // find the model (code not shown)
    return View(model);
}在Edit视图中,您不需要做任何特殊的事情,在“后操作”中
[HttpPost]
public ActionResult Edit(Model model)
{
    if (ModelState.IsValid)
    {
        // save Model...    
        return Redirect(Request.Params["returnUrl"]);
        // Request.Query will work as well since it is in the querystring
        // of course you should check and validate it as well...
    }
    // else return the View as usual, not shown
}要使用它,在从页面创建“编辑”链接时,只需指定额外的returnUrl参数:
@Html.ActionLink("Edit", "Edit",
    new { controller = "YourController", 
          returnUrl = Url.Action("Index", "ThisController",) 
        })希望能帮上忙。
https://stackoverflow.com/questions/25450178
复制相似问题