简体   繁体   中英

ASP.NET MVC: reassign TempData

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.

我认为您正在寻找TempData.Keep()

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:

  • Use a form variable (as you stated - and I'm guessing if it's a change password field then it may be sensitive)
  • Use a session variable (as you stated also!)
  • Persist the variable elsewhere in your application - custom database field or user profile or similar

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不是关键的信息安全性,则可以将其保留到“隐藏”字段(更改视图)并将其发布到下一个操作请求。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM