1

假设我有以下操作:

public ActionResult DoSomething()
{
    // Some business logic
    return RedirectToAction("AnotherAction", RouteData.Values);
}

public ActionResult AnotherAction(string name, int age)
{
   ...
}

以及以下形式:

<form method="post" action="DoSomething">
    <input name="name" type="text" />
    <input name="age" type="text" />
    <input type="submit" value="Go" />
</form>

在该表单上点击提交将转到DoSomething动作,然后转到另一个动作- 将所有相关值传递给nameage。这是一种享受!

我显然无法访问AnotherAction中的任何其他提交的表单值,因为从 DoSomething 重定向时它们会丢失:

public ActionResult AnotherAction(string name, int age)
{
   // This won't work
   var other = Request.Form["SomeDynamicVariable"];
}

更理想的是TransferToAction方法,它重新运行 MVC 引擎“想象”表单已发布到AnotherAction

return TransferToAction("AnotherAction");

我可以这样做吗?

如果此功能开箱即用不可用,那么我将制作它,将其发布到博客并发布!

4

4 回答 4

1

使用 TempData 构造来存储 Request.Form。TempData 仅针对给定的请求存在,因此在处理完成后将被清除。

public ActionResult DoSomething()
{
    // Some business logic
    TempData["PostedFormValues"] = Request.Form;
    return RedirectToAction("AnotherAction", RouteData.Values);
}

public ActionResult AnotherAction(string name, int age)
{
   ...
   if (TempData["PostedFormValues"] != null)
   {
       //process here
   }
}
于 2009-08-26T15:13:31.820 回答
1

您的控制器操作也是有效的公共功能,因此您可以这样做

public ActionResult DoSomething(){    
// Some business logic    
// Get Params from Request
      return AnotherAction(name, age);
}

public ActionResult AnotherAction(string name, int age){
   ...
}

当您现在从 AnotherAction 访问 Request 对象时,它仍然是相同的,因为您显然没有发出另一个请求。

于 2009-09-02T15:30:58.907 回答
0

您可以使用临时数据传递模型状态。拥有很少的 FilterAttributes 将真正简化流程,而且非常容易。

您应该阅读http://ben.onfabrik.com/posts/automatic-modelstate-validation-in-aspnet-mvc以正确使用过滤器属性。该博客还包含大量有关使用正确的 mvc 操作模型状态和 PRG 模式的信息。

这是一个更广泛的答案,不仅适用于您的具体情况,而且值得。

于 2013-04-10T18:48:47.373 回答
0

一种方法是从第一个动作调用第二个动作并捕获响应。正如这里所讨论的,这不是微不足道的。

于 2009-09-02T15:21:15.463 回答