Which option is better from Best practices point of view and from performance point of view?
views:
234answers:
5Local variable are store in the server memory and viewstate is stored in browswer(client side)
To decide which one used when look the following difference
--To reduce server memory load, prefred to store in viewstate
--To improve performance of page response in browser side, store it on variable
What do you need?
a variable that's alive from the moment the ASPX page gets created and starts its lifecycle and that will be disposed with the page instance once the HTML is rendered back to the client?
or a variable that will "survive" postbacks and be sent back to the client with the HTML and come back to the server the next time the page is requested??
For option #1, you're fine and should definitely use a normal variable inside your page class - no need for ViewState.
If you need option #2 - variable value needs to be saved across postbacks and come back with the next request - then there's only ViewState as an option - storing it in a local variable in your page class won't do.
Marc
Clearly local variables is a better option. They only exist while the method is running, and they are created on the stack so they are very cheap.
The ViewState is serialised and sent to the browser in a hidden field in the response, and returned to the server in the form data in the request. That is totally unneccesary if you don't need to persist the value.
(If you do need to persist the value, ViewState is the only option of the two. Local variables are of course not persisted from one request to the next.)
Another option if you need to persist variables is to let the containing page do it for you. Create an event on the user control that fires when your variables need populating then your page handles that event. You can get the best of both worlds in this way.
local variable : is persist for a life cycle of a single ASPX page
View state : the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across postbacks.
So based on the requirement you want to choose view state and local variable .