简体   繁体   中英

Razor MVC3 Keeping Global Variable Set on return to view

I have a global string variable that I set after one action is made (submit button is pressed) and then I want to access that same string when I press another button, currently I am doing something like

GlobalVariable = "blah";
return View();

What is the best practice for accessing this again. I would like to point out it is the same page(index.cshtml)

Thanks!

If its a per user value, use this:

Session["MyKey"] = "MyValue"; // save the value
var myValue = (string) Session["MyKey"]; // retrieve the value

If its one value for all users use this:

Application["MyKey"] = "MyValue"; // save the value
var myValue = (string) Application["MyKey"]; // retrieve the value

Hope this helps.

Are you really sure that you want every user of the site to share this state? This is quite a rare requirement. More likely it should be specific to the user.

There are few places in ASP.NET where you can save information:

  • Application - global scope, so the value is visible to all users.
  • Session - session scope, visible to one user
  • Cache - global scope, so the value is visible to all users.
  • TempData - visible to one user, during this and next request

Examples:

public ActionResult MyAction()
{
    HttpContext.Application["global_var"] = "anyone can see me";
    HttpContext.Cache["global_cached"] = "anyone can see me, but I can expire";
    Session["session_var"] = "only this user can see me";
    TempData["flash_var"]= "only this user can see me but also in next request";        
}

我不是ViewBag的粉丝,所以我的解决方案是将它添加到您传递给视图的视图模型中,并使用HiddenFor()以便在每个后续操作需要时将其发回。

将它放在ViewBag.GlobalVariable中

而不是在ASP MVC中使用Session甚至viebag,我建议在这种情况下使用Cashing

 Cache["permvaluetostore"] =valuetokeep

You need to persist that data. You may use either a database table or Session variable to do so.

Session variable value will be available to the current session .

If you want the value to be a global across all sessions, you may also consider using Caching .

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