asp.net-mvc - 将 View 数据保留在 RedirectToAction 上

标签 asp.net-mvc viewdata redirecttoaction

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateUser([Bind(Exclude = "Id")] User user)
{
        ...
        db.SubmitChanges();
        ViewData["info"] = "The account has been created.";
        return RedirectToAction("Index", "Admin");
}

在redirectToAction 之后,这不会在viewdata 中保留“信息”文本。
我将如何以最优雅的方式解决这个问题?

我目前的想法是将 Index controlleraction 中的内容放在 [NonAction] 中,并从 Index 操作和 CreateUser 操作中调用该方法,但我觉得必须有更好的方法。

谢谢。

最佳答案

您可以使用 TempData .
TempData["info"] = "The account has been created." .

TempData正是针对这种情况而存在的。它使用 Session 作为存储,但在第二次响应后它不会存在。

来自 MSDN:

A typical use for a TempDataDictionary object is to pass data from an action method when it redirects to another action method. For example, an action method might store information about an error in the controller's TempData property (which returns a TempDataDictionary object) before it calls the RedirectToAction method. The next action method can then handle the error and render a view that displays an error message.

关于asp.net-mvc - 将 View 数据保留在 RedirectToAction 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1226329/

相关文章:

asp.net-mvc - 没有类型为 'Blah' 的键为 'IEnumerable<SelectListItem>' 的 ViewData 项

asp.net-core-2.2 - Asp.Net核心Tempdata和redirecttoaction不起作用

ruby-on-rails - Redirect_to 从设计创建到模型创建 - 使用帮助程序 - 语法错误

javascript - asp .net jquery 在确认对话框后更改表行颜色

c# - 将 Azure B2C 与 MVC、.NET Core 3.1 结合使用

ruby-on-rails - ASP.NET MVC : Passing instance variables to the View like in Ruby

Viewdata 的 Javascript 错误

c# - ASP.NET MVC 回调后的 RedirectToAction

asp.net-mvc - ASP.NET MVC从数据库加载Razor View

c# - umbraco 中的 URL 重定向,当找不到文档时,重定向到其他地方