[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/