asp.net String not retained on postback
I am trying to create the following scenario...
- A user logs in by inserting their user id and password.
- If they don't have an email address assigned to their login details they are asked to submit one before they can continue.
- They then continue to the home page in a logged in state.
The trouble I'm having is that the user id and password are not retained when they submit their email address so the login fails.
Here's the code...
Dim userid as String
Dim password as String
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
end sub
Sub Page_Transfer()
Dim userLookup As mySource.myData = New mySource.myData()
Dim drSet1 As DataSet = userLookup.xyz("SELECT * FROM OPENQUERY (myDatabase,' SELECT userid, password, email1 FROM userInfo WHERE userid = ''" & userid & "'' AND password = ''" & password & "'' ') ")
If drSet1.Tables(0).Rows.Count < 1 Then
'Invalid Bond number
Page.ClientScript.RegisterClientScriptInclude("loginError", "scripts/loginError.js")
Else
If drSet1.Tables(0).Rows(0).Item("email1") = "" Then
'No email address
Page.ClientScript.RegisterClientScriptInclude("emailAddressSubmit", "scripts/emailAddressSubmit.js")
Else
response.redirect("home.aspx")
End If
End If
End Sub
Sub Submit_Email(sender As Object, e As System.Web.UI.ImageClickEventArgs)
'script to add email address to开发者_StackOverflow database
'this is where the strings are losing their values
Page_Transfer()
End Sub
Sub Submit_login(sender As Object, e As System.Web.UI.ImageClickEventArgs)
userid = Trim(useridfield.text)
password = Trim(passwordfield.text)
Page_Transfer()
End Sub
Any ideas?
The problem is that, with every postback, the page goes through a full new lifecycle. That means that any instance variables of your page which you set during one postback are lost in the next one.
How to solve this problem? You have the following options:
Read userid and password again from the controls (useridfield and passwordfield). Since ASP.NET controls use the view state to retain their values after postback, the value in these controls should still be valid.
Use the view state yourself to save the variable's values, i.e., replace
Dim userid as String Dim password as String
with
Protected Property userid As String Get Return DirectCast(Me.ViewState("userid"), String) End Get Set Me.ViewState("userid") = value End Set End Property ' same for password
Be aware, though, that the view state is not secure, i.e., it can be modified by a skilled user of your web application. Thus, be sure to validate the values of userid and password again (check the DB to see if they match) before assigning a mail address to them. (Same holds for option 1, by the way.)
Save the values somewhere else, for example, in the Session.
精彩评论