How to prevent the object from becoming null? - asp.net

I have the following code. During page load, I get the customer object from the database. After that when I try to access the same object in a different method, the object comes out as empty. Assume Student object has properties like firstName, lastName etc.
Public class Test
Public oStudent as Student
Public Sub Page_Load(ByVal sender as Object, ByVal e as System.EventArgs) Handles Me.Load
oStudent = getStudent(22) 'This is just a sample. This is not my actual database.
End Sub
Public Sub Update(ByVal sender as Object, ByVal e as System.EventArgs) Handles crtlStudent.Update
Update(oStudent)'This one updates makes a database call to update the studnet
End Sub
End class
When the page loads, the student is returned from the database correctly. However, when I'm on my update method, oStudent object becomes null/empty. Is this the way the page life cycle works? If yes, I would need to store the oStudent in a session or cache it right? Is there any other way to prevent the oStudent from becoming null other using session variables or caching it?

It is not the case that the object is null in the other method but after the page is disposed. That happens at the end of every page's lifecycle, so when it was rendered as HTML and sent to the client.
So you either have to re-initialize/load the object on every postback or persist it somewhere. In your sample-code you are loading it always in Page_Load, hence i doubt that it's null anywhere. So i guess that it's not the real code which could be:
Public Sub Page_Load(ByVal sender as Object, ByVal e as System.EventArgs) Handles Me.Load
If Not IsPostBack Then
oStudent = getStudent(22) ' in a button-click handler it will be null since it's a PostBack
End If
End Sub
Is there any other way to prevent the oStudent from becoming null
other using session variables or caching it?
Nine Options for Managing Persistent User State in Your ASP.NET Application

Related

How to share a variable value with a webmethod?

I have this code:
Dim main_id As int
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
main_id =1
End Sub
<WebMethod()> _
Public Shared Function BindPersonnel(ByVal product_id As String) As String
Dim project_id AS int16
project_id=main_id 'this doesn't work
End Function
On page load, I set the value of variable main_id and I need a way to somehow share the main_id with webmethod function, how can this be done? I have not tried session variable and I don't want to use session variable. I found this link Accessing a common variable in WebMethod and jQuery but I can't figure out how this is going to solve my problem. I also read some posts about using hidden field, which requires me to go two trips. I would love to avoid that.
WebMethods are independent of the other variables on the page. If you want to access main_id, you could declare it as Private Shared main_id As Integer, but that would then cause all of your users to have access to the same ID value, which you probably don't want.
Perhaps the easiest way to do this is to store the value in SessionState, and enable sessionstate access in the WebMethod. On the other hand, this removes the asynchronous-like functionality that you are looking for (it may not be an issue).
SessionState will give you the ability to have a per-session value (avoiding the use of the Shared solution mentioned above).
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Session("main_id") = 1
End Sub
<WebMethod(EnableSession:=True)>
Public Shared Function BindPersonnel(ByVal product_id As String) As String
Dim project_id As Integer = CInt(HttpContext.Current.Session("main_id"))
End Function

ASP.NET - Accessing web page twice from client

What happens if one user tries to access an ASP.NET page twice before the first page is returned to the client? Have a look at the code below:
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Session("ID") = 1
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Response.Redirect("Default3.aspx")
End Sub End Class
Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Session("ID") = 2
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Response.Redirect("Default3.aspx")
End Sub
End Class
Imports System.Threading
Partial Class Default3
Inherits System.Web.UI.Page
Dim intTest As Integer = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For intTest = 0 To 10
Response.Write(Session("ID") & " " & intTest & "<br>")
Thread.Sleep(1000)
Next
End Sub
End Class
Accessing default3.axpx from the same client (PC) concurrently from default.aspx (by clicking button) and default2.aspx (by clicking button) causes the session variable to be the same on both requests (though I set the variable to 1 on the first request and 2 on the second). Is it possible to replicate this behaviour without threading? I believe I have this bug in an asp.net application that does not use threading.
Your question is not about multi-threading; it is about SessionState.
ASP.NET run time uses lock to avoid overriding same session variables although it can handles multiple requests.
It's why you are do not see miss-matching results.
Please also look at -
ASP.NET Application and Page Life Cycle
ASP.NET Application Life Cycle Overview
It's important to understand that session information is stored at the application level, and really has nothing directly to do with a page.
You could compare it to a global variable in a class. If all your methods are reading and writing to this variable, it will always contain the information from the last time it was updated. It doesn't matter how many times, or which methods, updated it.
To help see this in your code, create a new class with one property. Change your session variable to be an object of this class. Modify your session logic to refer to this object instead of a string, and update the property.
Finally, put a break point on the setter of your property.
This will let you see whenever your session variable is updated, and with what value. You can also view your stack trace to see what's setting it.
-note, this is all assuming you aren't introducing a farm into this and are accessing session from different machines--

Help with refreshed ASP.NET page clearing public array

Hey all, i am new at everything VB.net/ASP.net so i need some help with a problem i am currently having.
I have an ASCX.vb page that lets the user choose someone from a table. Once they do select someone, the page reloads with that persons information into another table below that one where they can submit an order for that person or remove that person.
Problem being is that i wanted to store the users ID that are selected but it seems that everytime the page reloads to show an update, it dim's my array again back to default.
This is my code once they choose a user:
Namespace prog.Controls
Partial Public Class progReportGrid
etc....
Public strIDArray() As String = {"0000770000"} 'Just a dummy place holder
Private Sub gvData_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvData.RowCommand
Dim idIndexNumber As Integer = Array.IndexOf(strIDArray, strID)
For i As Integer = 0 To strIDArray.Length - 1
System.Diagnostics.Debug.WriteLine(strIDArray(i))
Next
If idIndexNumber = -1 Then
ReDim Preserve strIDArray(strIDArray.Length)
strIDArray(strIDArray.Length) = strID
RaiseEvent EmployeeSelected(Me, New ESEventArgs(strID))
End If
End Sub
So everytime to page reloads the Public strIDArray() As String = {"0000770000"} gets called again and, of course, clears anything that was saved to it other than 0000770000.
How can i keep it from doing this?
UPDATE
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'do what?
End If
End Sub
David
Perhaps you have a misunderstanding with the stateless model of a web application. Anything that is not stored in the ViewState or Session or a shared application variable will NOT persist through postbacks.
This means that when you declare your
Public strIDArray() As String
as a standard variable, it will be re initialized every time the page posts back.
For example, here's a simple flow of how this works:
The user opens their browser and opens up your aspx web page.
The request goes to your server, and all the controls including progReportGrid are instantiated as new instances and added to the page. (this is where your variable gets set to its original value every time)
A bunch of events are fired, including the Me.Load event
Controls that were added to the page are asked to generate their HTML
The HTML gathered from all the controls on the page is sent back to the user
So because your controls are all re-instantiated every post back, class variables like strIDArray are pretty much thrown out after the page is sent to the user.
Instead, if you want the page to remember what value the array had last postback and add more to it next postback, you have to use either ViewState, or Session.
For example:
Private Property StrIDArray() As String()
Get
If ViewState("StrIDArray") Is Nothing
ViewState("StrIDArray") = New String() {"0000770000"}
Return ViewState("StrIDArray")
End Get
Set(ByVal value As String())
ViewState("StrIDArray") = value
End Set
End Property
Now if you used this property instead of your variable, you could manipulate that array and as long as the user is on that page, the value of that array will persist across postbacks.
Use the Page.IsPostBack property in your Page_Load method.
This property is false for the first time the page loads and false for every postback afterwards.
If you set your default value strIDArray() = {"0000770000"} within If (Page.IsPostBack <> true) then it will not get reset on the postback.
EDIT : My VB syntax is VERY shaky but let me try it out
Partial Public Class EARNReportGrid
Begin
Public strIDArray() As String // DO NOT INITIALIZE it here. ONLY DECLARE IT
.....
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
//INITIALIZE the ARRAY
strIDArray = New String(){"00007700000"}
End If
End Sub
......
End

Preserve Data-structure on AJAX postback

Partial Class ClientCenter_UpdateSub
Inherits System.Web.UI.Page
Structure PInfo
Dim Name As String
Dim Surname As String
End Structure
Dim OldPInfo As New PInfo
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
'blah blah
OldPInfo.Name = Dt.Rows(0).Item("Name").ToString
OldPInfo.Surname = Dt.Rows(0).Item("Surname").ToString
end if
end sub
End Class
The first time the page loads my structrure is filled correctly.
After an AJAX postback all the structure fields are setting to nothing. (It seems that the Dim OldPInfo As New PInfo is called again), but i should better ask the SO Experts.
So anyway, what am i doing wrong here?
First off, You should never assign a variable outside of a property or a method.
Second, web applications are stateless (which means NOTHING is automatically saved from call to call - unless you store it somewhere like Viewstate, Session, etc.).
Remember to accept this answer if it helps solve your problem.

How to Persist Variable on Postback

I created a single page (with code behind .vb) and created Public intFileID As Integer
in the Page load I check for the querystring and assign it if available or set intFileID = 0.
Public intFileID As Integer = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not Request.QueryString("fileid") Is Nothing Then
intFileID = CInt(Request.QueryString("fileid"))
End If
If intFileID > 0 Then
GetFile(intFileID)
End If
End If
End Sub
Private Sub GetFile()
'uses intFileID to retrieve the specific record from database and set's the various textbox.text
End Sub
There is a click event for the Submit button that inserts or updates a record based on the value of the intFileID variable. I need to be able to persist that value on postback for it all to work.
The page simply inserts or updates a record in a SQL database. I'm not using a gridview,formview,detailsview, or any other rad type object which persists the key value by itself and I don't want to use any of them.
How can I persist the value set in intFileID without creating something in the HTML which could possibly be changed.
[EDIT] Changed Page_Load to use ViewState to persist the intFileID value
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not Request.QueryString("fileid") Is Nothing Then
intFileID = CInt(Request.QueryString("fileid"))
End If
If intFileID > 0 Then
GetFile(intFileID)
End If
ViewState("intFileID") = intFileID
Else
intFileID = ViewState("intFileID")
End If
End Sub
As others have pointed out, you can store it in the Session or the ViewState. If it's page specific, I like to store it in the ViewState as opposed to the Session, but I don't know if one method is generally preferred over the other.
In VB, you would store an item in the ViewState like:
ViewState(key) = value
And retrieve it like:
value = ViewState(key)
Store in:
Session
ViewState
Hidden input
Just to summarize what is said above.
You can use Session, Viewstate, or a hidden field.
I personally prefer viewstate as it will work in web farm environments, Session does not, it does not store it on the server waiting for the user, for up to 20 minutes to be removed, and in general viewstate is the place to be for page level data.
You can use a hidden field, but then a user could more easily modify it.
Store it in the Session.
Page.Session["MyPage_FileID"] = intFileID
You'll need to have logic that manages it as the user navigates around, but if it is always set when the page loads from a GET (or you clear it, if not available on GET) then you should be ok using it later from the Session on your submit PostBack.
Remember:
Each time your server code runs, it's in a brand new instance of your page class. That's for every postback.
Actually, since an ASP.NET page postbacks to itself - including the query string - you could just remove the If Not Page.IsPostBack condition. Then it'd set itself on each postback.
I personally would choose to store the value in control state instead of viewstate as viewstate can easily be switched off. ControlState will persist even if viewstate is switched off for any reason. I have included an example on how this may be done.
Private intFileId As Integer = 0
Public Property FileID() As Integer
Get
Return intFileId
End Get
Set(ByVal value As Integer)
intFileId = value
End Set
End Property
Protected Overrides Function SaveControlState() As Object
Dim objState(2) As Object
objState(0) = MyBase.SaveControlState()
objState(1) = Me.FileID
Return objState
End Function
Protected Overrides Sub LoadControlState(ByVal savedState As Object)
Dim objState() As Object
objState = savedState
MyBase.LoadControlState(objState(0))
Me.FileID = CInt(objState(1))
End Sub
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Me.Page.RegisterRequiresControlState(Me)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not String.IsNullOrEmpty(Request.QueryString("fileid")) Then
Me.FileID = CInt(Request.QueryString("fileid"))
End If
End If
Response.Write(Me.FileID.ToString())
End Sub
Session["KeyName"] = your value;
Type cast to the type to retrieve and store the data from session like given below :
Datatable dt = (DataTable)(Session["KeyName"]);
or
ViewState["KEY"]= value;
Type cast to the type to retrieve and store the data from session like given below :
String str = (String)ViewState["KEY"];
I'll use Session as suggested by tvanfosson.
ViewState and HiddenField might be too heavy if you want to keep large data like a dataset for comments in a forum's topic pages..

Resources