Reputation: 7261
I have a TextBox control and I want the rendered input element to have the readonly
attribute with value readonly
:
<input type="text" readonly="readonly" />
I could do it in code-behind using the following code:
textBox.Attributes["readonly"] = "readonly"
but I'd rather have all my control attributes and their values in my markup. Can I do it in the markup?
A solution could be to extend the TextBox control, but this feels overly complicated for the intended result.
I want to be able to change the value client-side with javascript, and read the value server-side during postbacks. Please note that putting the TextBox.ReadOnly
property to True
would not solve the issue, as this also causes the server to ignore the TextBox' value on postbacks. (MSDN.) I simply want the readonly behavior from the browser.
Upvotes: 0
Views: 3437
Reputation: 7261
It seems you can't do it cleanly in the markup without getting ASP.NET's ReadOnly
side effects.
However, you could use inline code, although it looks ugly.
<asp:TextBox runat="server" ID="textBox" />
<% textBox.Attributes["readonly"] = "readonly"; %>
Upvotes: 0
Reputation: 995
One possible way is to use a Hidden Field. As you change the value of the ReadOnly TextBox in javascript, change the value also of the Hidden Field and then access the value of the Hidden Field in the Server Side
Upvotes: 0
Reputation: 5579
The following creates a readonly textbox where the value of the text is available to the codebehind.
Markup:
<asp:TextBox ID="Text1" runat="server" Text="One Two Three" ReadOnly="true" />
Code Behind (C# for this example):
string someText = string.Empty;
if (Page.IsPostBack)
someText = Text1.Text;
Upvotes: 1