How to make textbox readOnly

2020-05-03 12:02发布

问题:

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

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

回答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.