将视图数据保留在RedirectToAction上 [英] keep viewdata on RedirectToAction

查看:89
本文介绍了将视图数据保留在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之后,这不会在视图数据中保留信息"文本. 我如何以最优雅的方式解决这个问题?

This doesnt keep the "info" text in the viewdata after the redirectToAction. How would I get around this issue in the most elegant way?

我目前的想法是将Index控制器动作中的内容放入[NonAction]中,并从Index动作和CreateUser动作中调用该方法,但是我觉得必须有更好的方法.

My current idea is to put the stuff from the Index controlleraction in a [NonAction] and call that method from both the Index action and in the CreateUser action, but I have a feeling there must be a better way.

谢谢.

推荐答案

您可以使用TempData.

TempData["info"] = "The account has been created.".

TempData 正是针对这种情况而存在.它使用会话作为存储空间,但是不会在第二次响应后出现.

TempData exists exactly for this situation. It uses Session as storage, but it will not be around after the second response.

从MSDN:

TempDataDictionary对象的典型用法是当它重定向到另一个动作方法时,从该动作方法传递数据.例如,一个动作方法可能会在调用RedirectToAction方法之前在控制器的TempData属性(返回TempDataDictionary对象)中存储有关错误的信息.然后,下一个操作方法可以处理错误并呈现显示错误消息的视图.

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.

这篇关于将视图数据保留在RedirectToAction上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆