C# ASP.NET MVC 中的 Post/Redirect/Get 模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2120882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Post/Redirect/Get Pattern in ASP.NET MVC
提问by Charles
What is the best practice for implementing the Post/Redirect/Get pattern in ASP.NET MVC? In particular, what is the best way to do this when you want to redirect back to the initial action/controller?
在 ASP.NET MVC 中实现 Post/Redirect/Get 模式的最佳实践是什么?特别是,当您想重定向回初始动作/控制器时,执行此操作的最佳方法是什么?
Here's how I am currently doing this:
这是我目前的做法:
- Display form to user.
- In the form, use
<%= Html.Hidden("returnUrl") %>
- In the action, use
ViewData["returnUrl"] = Request.Url;
- In the form, use
- User submits the form via POST
- Redirect to the
returnUrl
model-binding, if notnull
. Otherwise, redirect to homepage.
- 向用户显示表单。
- 在表格中,使用
<%= Html.Hidden("returnUrl") %>
- 在动作中,使用
ViewData["returnUrl"] = Request.Url;
- 在表格中,使用
- 用户通过 POST 提交表单
returnUrl
如果不是,则重定向到模型绑定null
。否则,重定向到主页。
This get's the job done, but it feels like this would result in a lot of duplication. I also realized that I could probably redirect to Request.UrlReferrer
...
这样就完成了工作,但感觉这会导致很多重复。我也意识到我可能可以重定向到Request.UrlReferrer
......
What do you suppose is the cleanest, most ideal method of accomplishing this?
你认为最干净、最理想的方法是什么?
采纳答案by Scott Anderson
The way you're doing this is fine, but it looks like you might be overthinking it a little bit. Do your POST actions take form posts from more than one form? If not, why bother with a hidden form field? You could get away with a simple RedirectToAction("MyAction")
你这样做的方式很好,但看起来你可能有点想多了。您的 POST 操作是否从多个表单中获取表单帖子?如果没有,为什么要使用隐藏的表单字段呢?你可以摆脱一个简单的RedirectToAction("MyAction")
回答by G-Wiz
Typically, an action that handles a POST knows where it needs to redirect upon successful submission. Therefore, each action that implements RGP can simply invoke RedirectToAction(string)
.
通常,处理 POST 的操作知道成功提交后需要重定向的位置。因此,每个实现 RGP 的操作都可以简单地调用RedirectToAction(string)
.
public ViewResult Edit(string email)
{
// save the email
return RedirectToAction("Edit");
}