I'm getting a DataTable from a DataBase and assigning to ViewState like below: Because I don't want to hit the database for every time.
DataTable dt = GetDataTable();
ViewState["dtTable"] = dt;
GetDataTable()
is a method, which retrieves 1000 records from the DataBase.
Is this the best way or which one is the best way to handle this?
First things first: Explanations aside, It still depends a lot on your requirements, environments settings ...
The viewstate is stored in a hidden field rendered as <input />
tag in final HTML sent to browser . When the user initiates a postback ( Button Click etc..), the data is sent back to the server as part of the submitted form data.
If you store large amounts of data in the ViewState, you will have to incur a penalty when the user attempts to download the page because all such data will be part of your HTML and also when the user attempts to submit the form because again this data will be sent back to server.
In addition, the ViewState is easily lost. It is only preserved as long as the user is submitting the form. If the user clicks a hyperlink to another page, the form is not submitted and therefore data contained within the ViewState is lost.
It is recommended to use ViewState is if the data is relatively small.
If we consider security options, ViewState data is encoded in base64 , which can be easily decoded. This is a classic example for hacking a website, so crosscheck as to what data exactly you are storing. Although you can overcome this issue by setting EnableViewStateMac
to true.
For large amounts of data, Session is a good option. If you are able to detect when any user is done with a particular block of data, set the Session variable to null, to counter memory overhead. You can't always do this, but Also the Session will expire and the memory will be reclaimed automatically. Lowering the Session timeout can also help but set it as per the requirement needs.
Also,the data in the Session is actually present on the web server between page loads. This helps in keeping the page size small, it only has to utilize the Session ID.
One last option is to use Caching.Check MSDN here for the best practices on Caching.