ASP.NET TextBox 設定 TextMode="Password" 時,為了安全性,瀏覽器不會在 HTML 中輸出 value 屬性,導致後端程式碼指派 Text 屬性無效,前端顯示為空白。
<asp:TextBox ID="txtPwd" runat="server" TextMode="Password" ClientIDMode="Static" />
<script>
// 後端產生腳本或透過 RegisterStartupScript
document.getElementById('txtPwd').value = '<%= Server.HtmlEncode(PasswordValue) %>';
</script>
attributes 強制輸出txtPwd.Attributes["value"] = passwordValue;
此法會直接在渲染的 <input> 標籤加上 value,但需注意:瀏覽器開發工具可見明碼,僅適用於非高敏感度場景。
public class PasswordTextBox : TextBox {
protected override void Render(HtmlTextWriter writer) {
if (!string.IsNullOrEmpty(Text))
Attributes["value"] = Text;
base.Render(writer);
}
}
封裝邏輯,專案中複用極為方便。
autocomplete="off")掌握上述技巧,即可在保有安全性前提下,靈活處理 Password 欄位的後端賦值需求。