April 28, 2010 by Christoff Truter C# ASP.NET
If you ever migrated from ASP.net 1.0 to ASP.net 2.0, you might have noticed the following
issue.
Imagine you've got a page like the following one:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> function populate() { var txtTest = document.getElementById("<%=txtTest.ClientID %>"); txtTest.value = "test 123"; } </script> </head> <body> <form runat="server"> <div> <asp:TextBox runat="server" ID="txtTest" ReadOnly="true" Text="abc"></asp:TextBox> <input type="button" onclick="populate()" value="Test" /> <br /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> </div> </form> </body> </html>
txtTest.Attributes.Add("readonly", "readonly");
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.WebControls.Adapters; using System.Web.UI.WebControls; namespace CSTruter { public class TextBoxAdapter : WebControlAdapter { protected override void OnInit(EventArgs e) { TextBox sender = this.Control as TextBox; if (sender.Attributes["secure"] == null) { if (sender.ReadOnly == true) { sender.ReadOnly = false; sender.Attributes.Add("readonly", "readonly"); } } base.OnInit(e); } } /* Since the value of a multiline textbox doesn't persist when we create an adapter, we need to do the following */ protected override void Render(System.Web.UI.HtmlTextWriter writer) { TextBox sender = this.Control as TextBox; base.RenderBeginTag(writer); if (sender.TextMode == TextBoxMode.MultiLine) { System.Web.HttpUtility.HtmlEncode(sender.Text, writer); } else { base.RenderContents(writer); } base.RenderEndTag(writer); } }
<asp:TextBox runat="server" ID="txtTest" Text="abc" Secure="true"></asp:TextBox>