开发者

ASP.NET MVC: reassign TempData

开发者 https://www.devze.com 2023-04-04 05:47 出处:网络
In a controller action I receive a variable from a redirect in a TempData variable public ActionResult ChangePassword()

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 wante开发者_运维技巧d 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.


I think you're looking for 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...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消