Wednesday, 12 October 2011

Setting the Value of a TextBox when TextMode=Password from code behind in ASP.Net

When the TextMode property of an ASP.NET TextBox is set to Password the value set in the Text property will not display at runtime.
This can be a pain; however it is actually by design to prevent the unmasked password from being displayed in the HTML source of the page.
While the security reasons are good to not display the masked password value, leaving it unmasked in the source, it is also necessary at times to display the masked value in the TextBox. For example, a user profile page where the user has the ability to change their password. It makes sense to display it there. After all, the user has already authenticated to get to the page (although the value is sent with the data to the browser and could easily be sniffed).
Security reasons aside, you can work around this by adding the password value to the control as Attribute. Since the TextBox renders as an HTML input control, you can set the value attribute easily, just as you would set the Text property.

Inline HTML:
<asp:textbox ID="txtPassword" runat="server" TextMode="Password"></asp:textbox>
Code Behind:
this.txtPassword.Attributes.Add("value", "password");

No comments:

Post a Comment