ASP.NET MVC:重新分配 TempData
在控制器操作中,我从 TempData 变量中的重定向接收一个变量
public ActionResult ChangePassword()
{
string t = (string)TempData["myVariable"]; // works ok when coming from the redirect
[..]
}
,因为我需要为另一个调用保留该数据,所以我尝试在返回视图之前重新分配它。
public ActionResult ChangePassword()
{
string t = (string)TempData["myVariable"];
[..]
TempData["myVariable"] = TempData["myVariable"];
return View();
}
我立即从呈现的页面向 ChangePassword 提交 POST 请求,但这次 TempData["myVariable"] 为 null。也许我做了一些愚蠢的事情,但是如何获得想要的结果呢?我不想使用会话变量(它会持续更长时间,我将努力确保手动清除该变量以防止会话变量的污染)。我可以通过表单(隐藏变量)重新发布它,但我更愿意仅将变量保留在服务器端。
In a controller action I receive a variable from a redirect in a TempData variable
public ActionResult ChangePassword()
{
string t = (string)TempData["myVariable"]; // works ok when coming from the redirect
[..]
}
As I need to persist that datum for another call, I try to reassign it before returning the view.
public ActionResult ChangePassword()
{
string t = (string)TempData["myVariable"];
[..]
TempData["myVariable"] = TempData["myVariable"];
return View();
}
I immediately submit a POST request from the rendered page back to ChangePassword, but this time TempData["myVariable"] is null. Maybe I'm doing something stupid, but how to get the wanted result? I don't want to use a Session variable (it would persist much longer and I'd be working on ensuring manually that the variable is cleared to prevent the pollution of Session variables). I could repost it via the form (a hidden variable) but I'd prefer to keep the variable only server-side.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您正在寻找
TempData.Keep()
I think you're looking for
TempData.Keep()
TempData 仅在当前请求的上下文中持续存在。如果您将内容返回给客户端,然后客户端又发回内容,则您无法使用它。您的选项非常标准,基本上仅如您所描述的那样:
内容我个人会选择会话提供程序,或者尝试避免将内容返回给客户端并立即回发,如果可能的话......
TempData only persists within the context of the current request. If you are returning content to the client, and then the client is posting back, you can't use that. Your options are pretty standard, and basically only as you described:
Personally I'd go with a session provider, or try to avoid returning content to the client with the immediate post back altogether, if possible...
如果 myVariable 不是关键信息安全,您可以将其保留到隐藏字段(更改视图)并将其发布到下一个操作请求。
If myVariable is not a critical information security you can persit it to Hidden field (change the view) and post it to next action request.