C# 在asp.net 回发之间保存变量的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10138480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:36:11  来源:igfitidea点击:

Best way to save variables between postbacks asp.net?

c#asp.net.net

提问by Endiss

How can I save variables in asp.net between postback? I'm using HttpContext.Current.Items but it always disposes after postback is there any other option to do that?

如何在回发之间在asp.net中保存变量?我正在使用 HttpContext.Current.Items 但它总是在回发后处理有没有其他选择可以做到这一点?

采纳答案by Adil

ViewState["YourVariable"] = "123";

ViewState collection is mean for this purpose, in above example YourVariable is a variable whoes value you want to save and 123 is value of this variable.

ViewState 集合就是为了这个目的,在上面的例子中,YourVariable 是一个你想要保存的值的变量,123 是这个变量的值。

ViewState is accessible within the scope of page. If you want to have values between different pages you can use sessions like ViewState["YourVariable"] = "123";

ViewState 可在页面范围内访问。如果你想在不同页面之间有值,你可以使用像 ViewState["YourVariable"] = "123"; 这样的会话。

回答by jbl

If your variable is not serializable or you do not want the client to be able to read its value => use inProc Session

如果您的变量不可序列化或者您不希望客户端能够读取其值 => 使用 inProc Session

If your variable is serializable and you do not want the client to be able to read its value => use database Session

如果您的变量是可序列化的并且您不希望客户端能够读取其值 => 使用数据库会话

if your variable is serializable, and you can live with the client reading its value, and it should only live during the postbacks sequence in the scope of the page => you should use ViewState.

如果您的变量是可序列化的,并且您可以让客户端读取其值,并且它应该只在页面范围内的回发序列期间存在 => 您应该使用 ViewState。