How to protect an asp:textbox from user input?

DreamTeK picture DreamTeK · Feb 28, 2014 · Viewed 8.7k times · Source

How to protect an asp:textbox from user input?

DISABLE IT

<asp:TextBox ID="txbx" runat="Server" Text="1" Enabled="false" />

PROTECT IT

<asp:TextBox ID="txbx" runat="Server" Text="1" ReadOnly="true" />

I wish to protect the textbox as above from user input but still allow the value to be updated with javascript.

This works fine so what's the problem?

THE PROBLEM

If a textbox is disabled or readonly the updated values will not post to the server when submitted!

QUESTION

How to create a textbox that can simultaneously:

  • Be visible to the user.

  • Be protect from user input.

  • Be updated with javascript.

  • Post updated value to server.


ANSWER

The conflict occurs because when you set enabled="false" on control it is does not pass the values to the server.

However setting disabled or readonly clientside does not cause this issue.

You can set the properties clientside by using:

In code behind:

txbx.Attributes.Add("ReadOnly", "ReadOnly")
txbx.Attributes.Add("disabled", "disabled")

or by using client side controls and setting them to runat server:

<input type="text" id="txbx" readonly="readonly" runat="server" />
<input type="text" id="txbx" disabled="disabled" runat="server" />

Answer

Atanu Roy picture Atanu Roy · Feb 28, 2014

I once got out of this situation by setting the ReadOnly property from code-behind. You can try this once.

txbx.Attributes.Add("ReadOnly", "ReadOnly");

Add this line of code in your Page_Load event.

Please inform if it works for you.