Can I set text box to readonly when using Html.TextBoxFor?
I have the following tag with a Html.TextBoxFor expression and I want the contents to be read only, is this possible?
<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action)%>
Solution 1:
<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new { @readonly = true })%>
Solution 2:
Use the following:
@Html.TextBoxFor(m => m.Whatever, new {@readonly = "readonly"})
If you want to assign a class to it you could do it the same way , by adding the @class = "" property. Hope this helps :)
Solution 3:
Updated for modern versions of .NET per @1c1cle's suggestion in a comment:
<%= Html.TextBoxFor(model => Model.SomeFieldName, new {{"readonly", "true"}}) %>
Do realize that this is not a "secure" way to do this as somebody can inject javascript to change this.
Something to be aware of is that if you set that readonly
value to false
, you actually won't see any change in behavior! So if you need to drive this based on a variable, you cannot simply plug that variable in there. Instead you need to use conditional logic to simply not pass that readonly
attribute in.
Here is an untested suggestion for how to do this (if there's a problem with this, you can always do an if/else):
<%= Html.TextBoxFor(model => Model.SomeFieldName, shouldBeReadOnlyBoolean ? new {{"readonly", "true"}} : null) %>
Solution 4:
To make it read only
@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @readonly="true"})
To diable
@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @disabled="true"})