Tuesday, February 12, 2008

Retain Password in ViewState

Recently, while working on one assignment, there was a total new and funny situation I came across. I was working on User Registration Page, It was typical User Registration Page.

First few fields was like Username,Firstname etc. then it was Password field. Below that I was filling two combo boxes of City and State which was dependable on each other..So I was not having any choice but to post them back and fire SelectedIndex change event..All of the other information like Username,Firstname was in state and were able to retain their values which I key in them..but
don't know how..Password field was getting blank again and again.

One of my friend told me that this is because of Security reason,that we lost value in Password Textbox in Postback of page..Some people told me that its next to impossible to retain Password value in Postbacks and might be dangerous and against security policies.

But..I was not having choice as it was my task..so I tried out whole tons of experiment..All Sessions, Varibles,Constants,JavaScripts,HiddenFields,Enable ViewState..all stuff got simply failed..I was like no where..I then Google it..done few hits on Live engine and Yahoo..

Suddenly,I came across ViewState declarations on some forums..and It clicked.!!
I just wrote following piece of code and my 3 days research work got over finally..

ViewState["MyPassword"] = txtPassword.Text;
txtPassword.Attributes.Add("value",ViewState["MyPassword"].ToString());


and done with it..!!

Vikram.

2 comments:

Chaitanya said...

Hey I came across with the same situation while working with registration process. There was two combo boxes one is for Country and another is for States/province which is filled up according to the value selected in Country.

Its not require to store value in ViewState["MyPassword"] ... you can assign value to a simple variable in SelectedIndexChanged event as the first statement and assign back to the control in last statement and it worked ... following is the snippet of code i have written in my project:

Private Sub ddlCountry_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlCountry.SelectedIndexChanged
Dim sPassword As String = txtPassword.Text.Trim()

'Snippet of code to fill up state dropdown

'Setting password
txtPassword.Attributes.Add("value", sPassword)
End Sub

and this is working fine ...

Vikram Pendse said...

Thanks Chaitanya for your valuable feedback.

My concern that time was to maintain it in Postbacks, which generally txtbox with password don't allow to do so.

However,I will check if the same logic work for TextBox,especially if it is password textbox. For several Security reasons if you wish to store Password(Not the other text in combo or any sever control)then it becomes issue.

I will surely try to check it with some text as password in textbox. However concern remains for password is to keep it as it is in postbacks.