2

This is some code behind for an aspx page. I'm not sure if I should be using public variables or a 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? It seems like they both achieve the same thing.

2
  • A public variable will not work because that class is destroyed and re-created between each request.
    – Nate Zaugg
    Feb 21, 2013 at 18:45
  • @NateZaugg, I didn't even think about that but now that you said that it makes perfect sense. Thanks
    – Kevin
    Feb 22, 2013 at 16:15

3 Answers 3

4

Use ViewState if you want the values to persist between postbacks.

If the values only need to exist for the lifetime of the page, regular variables will do just fine.

1

The ViewState is used to persist the state of the WebForm across PostBacks. 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. Public variables will be reset with every PostBack unless you save their values in the ViewState or the SessionState, etc...

More info:

Understanding Asp.Net ViewState

Best way to save variables between postbacks asp.net?

1

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. Additionally you can create accessors that make it easy to access these values later (please excuse my C# syntax):

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)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.