简体   繁体   English

vb.net viewstate与公共变量

[英]vb.net viewstate vs public variable

This is some code behind for an aspx page. 这是aspx页面的一些代码。 I'm not sure if I should be using public variables or a viewState 我不确定是否应该使用公共变量或viewState

Partial Class madeUpName
 Inherits System.Web.UI.Page
  Public vin As String = ""
  Public stk As String = ""

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  'inside of here i use the variables
 end sub

 Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
  'inside of here I also use the same variables
 end sub

Should I use viewState variables or public variables in my class for the page? 我应该在页面的类中使用viewState变量还是公共变量? It seems like they both achieve the same thing. 看起来他们俩都实现了同一件事。

Use ViewState if you want the values to persist between postbacks. 如果希望这些值在回发之间保持ViewState ,请使用ViewState

If the values only need to exist for the lifetime of the page, regular variables will do just fine. 如果只需要在页面的生存期内存在这些值,则常规变量就可以了。

The ViewState is used to persist the state of the WebForm across PostBacks . ViewState用于在PostBacks之间保留WebForm的状态。 If you are looking to obtain values from your WebForm into your code behind, then do use ViewState values, otherwise you can use the SessionState or depending on the data you are trying to access you can use Cookies or even the QueryString . 如果您希望从WebForm的后面获取代码中的值,请使用ViewState值,否则可以使用SessionState或根据要访问的数据使用CookiesQueryString Public variables will be reset with every PostBack unless you save their values in the ViewState or the SessionState , etc... 除非将公共变量的值保存在ViewStateSessionState等中,否则公共变量将随每个PostBack重置。

More info: 更多信息:

Understanding Asp.Net ViewState 了解Asp.Net ViewState

Best way to save variables between postbacks asp.net? 在两次回发之间保存变量的最佳方法asp.net?

If the information is not very sensitive you can store them in hidden inputs: 如果信息不是很敏感,则可以将其存储在隐藏的输入中:

<input type="hidden" name="myvar" value="123" />

I tend to prefer that over putting stuff in the ViewState . 我倾向于将其放置在ViewState Additionally you can create accessors that make it easy to access these values later (please excuse my C# syntax): 另外,您可以创建访问器,以便以后轻松访问这些值(请原谅我的C#语法):

public int MyValue
{
    get { return int.Parse(Request["myvar"]); }
}

When you can use it in your class like a property. 何时可以在类中像属性一样使用它。

Otherwise you can put stuff in the ViewState (similarly) 否则,您可以将东西放入ViewState (类似)

public int MyValue
{
    get { return int.Parse(ViewState["myvar"]); }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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