How to make textbox readOnly

All we need is an easy explanation of the problem, so here it is.

How do I make this a readOnly textBox, and the text inside it appear as gray?

<%=  Html.TextBox("name")%>

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

If you don’t have an initial value you can as well provide only attributes anonymous object with relevant attribute set as

<%=  Html.TextBox("name", null, new { @readonly = true })%>
<!-- or -->
<%=  Html.TextBox("name", null, new { @readonly = "readonly" })%>

If you do have a value to set to this text box these two should be

<%=  Html.TextBox("name", "Some textbox value", new { @readonly = true })%>
<!-- or -->
<%=  Html.TextBox("name", "Some textbox value", new { @readonly = "readonly" })%>

The thing is that such attributes as readonly or hidden should be set without any value (according to specification), but you can’t provide such attributes using standard Html helper methods. The good thing though is that you can set anything as a value. But for the sake of readability and making them meaningful it’s best to set them either to true or attribute name as shown in my example.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply