Can I set text box to readonly when using Html.TextBoxFor?

后端 未结 15 1527
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 18:07

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.E         


        
相关标签:
15条回答
  • 2020-12-08 18:49

    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) %>
    
    0 讨论(0)
  • 2020-12-08 18:53

    In case if you have to apply your custom class you can use

      @Html.TextBoxFor(m => m.Birthday,   new Dictionary<string, object>() { {"readonly", "true"}, {"class", "commonField"} } )
    

    Where are

    commonField is CSS class

    and Birthday could be string field that you probably can use to keep jQuery Datapicker date :)

    <script>
                 $(function () {
                     $("#Birthday").datepicker({
    
                     });
                 });
      </script>
    

    That's a real life example.

    0 讨论(0)
  • 2020-12-08 18:53
       @Html.TextBoxFor(model => model.IdUsuario, new { @Value = "" + User.Identity.GetUserId() + "", @disabled = "true" })
    
    @disabled = "true"
    

    Work very well

    0 讨论(0)
  • 2020-12-08 18:54
    <%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new {readonly=true})%>
    
    0 讨论(0)
  • 2020-12-08 18:57

    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"})
    
    0 讨论(0)
  • 2020-12-08 18:58
    <%: Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new { @autocomplete = "off", @readonly=true})%>
    

    This is how you set multiple properties

    0 讨论(0)
提交回复
热议问题