Web Code Blog

A web repository of coding tips and knowledge base articles

Populating a Textbox with JavaScript and ASP.NET code-behind thinks it is empty?

Posted by Stefan Zvonar on April 14, 2010

So, you have placed a textbox onto your web page and populate the textbox using some JavaScript. However, when you submit the form, ASP.NET seems to think that the textbox is empty?

Well, chances are you have probably tried to disable the textbox – most probably because you are trying to stop the user from entering or changing the text themselves. However, there is a solution to this.

As an example, you may have set the ReadOnly attribute on the textbox like the below:

<asp:TextBox ID="txtSomeTextBox" runat="server" TextMode="MultiLine" ReadOnly="true"></asp:TextBox>

Or you may have set the Enabled property to false like the below:

<asp:TextBox ID="txtSomeTextBox" runat="server" TextMode="MultiLine" Enabled="false"></asp:TextBox>

Continuing with the example, you may have a button on the page that populates the above textbox. Something like the below:

<script language="javascript" type="text/javascript">
    function doSomething() {
        document.getElementById('<%=txtSomeTextBox.ClientID %>').value = "abcdefg";
    }
</script>

<input type="button" value="Do Something" onclick="doSomething();" />

When it comes to reading the textbox from the code-behind, ASP.NET thinks the textbox is empty. That is because you have actually set the server control to be unchangable.

A workaround is to simply to append the readonly attribute from within the code-behind, as shown below:

If Not IsPostBack Then
   txtSomeTextBox.Attributes.Add("readonly", "readonly")
End If

That should have the desired effect of still not letting your users change the textbox text and still allowing ASP.NET to read the populated text.

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Advertisement

One Response to “Populating a Textbox with JavaScript and ASP.NET code-behind thinks it is empty?”

  1. judson said

    My god thanks. I’ve running back and forth with this. IMO, ASP.Net – now including jquery – should always check for the value in this instance. The user may not be able to manually change the values, but javascript sure can.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.