32

I have two different ways to use a DISABLED TextBoxFor, which is:

@Html.TextBoxFor(u => u.Visibilidade, new { disabled = "disabled", @readonly = "readonly" })

and

@Html.TextBoxFor(u => u.Visibilidade, new { disabled = "disabled" })

ie. using or not readonly property

What is the difference, considering that a disabled field will not be changed any way?

Thanks in advance

Vlad Z.
  • 3,401
  • 3
  • 32
  • 60
Felipe Athayde
  • 397
  • 1
  • 4
  • 8
  • possible duplicate of [What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?](http://stackoverflow.com/questions/7730695/whats-the-difference-between-disabled-disabled-and-readonly-readonly-for-ht) – jamesSampica Feb 27 '14 at 00:07

2 Answers2

63

Usually you would use one or the other, not both.

Readonly allows users to focus on the textbox to copy text or trigger an event. Readonly fields will be posted with the form.

With a disabled field, users cannot give focus to the textbox and the field will NOT be posted with the form.

Which one you use depends on what you need to do with the field.

If you want to enable focus but don't want it posted, you can make it readonly, but override the name property.

@Html.TextBoxFor(u => u.Visibilidade, new { @readonly = "readonly", @Name = "" })
Brandon
  • 68,708
  • 30
  • 194
  • 223
  • Thank you. What if I would like the user to be able to focus on the textbox, but don't want its content to be posted with the form? That is a bit of both. – Felipe Athayde Feb 27 '14 at 17:22
  • 1
    @FelipeAthayde, the only thing I can think of is to not assign the field a `name` property. See update. – Brandon Feb 27 '14 at 19:19
0

Note: If you want it to be disabled, but you do want the original value to be posted with the form, you can use a HiddenFor along with your TextboxFor (with id set to null so the browser console doesn't complain about duplicate ids):

@Html.TextBoxFor(u => u.Visibilidade, new { @disabled = "disabled"})
@Html.HiddenFor(u => u.Visibilidade, new { id = null });

This way, the value from the HiddenFor will be posted with the form, but the textbox will be displayed as disabled.

Taraz
  • 1,242
  • 13
  • 13