Maybe not so obvious

March 25, 2009 13:27 by randy

I know this might sound a bit on the obvious side, but …

When using an ASP text box, with the read only setting set to True, any value in the text property (with client side JavaScript perhaps) will be ignored on post back.

Example

The following code:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>TextBox ReadOnly Demo</title>
    <script type="text/javascript">
     
            function replaceText() {
                var tBox = document.getElementById('<%=Target.ClientID%>');
                tBox.value = 'foo';
            }
        
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="Target" runat="server"  ReadOnly="true"/>
        <input id="htmlBtn" type="button" value="Populate TextBox" onclick="Javascript:replaceText();"  />        
        <asp:Button ID="Go" runat="server" Text="Go!" onclick="Go_Click" />
    </div>
    </form>
</body>
</html>

This will open a simple web page with two buttons and a textbox control.

The first button is an HTML input button.  It fires a JavaScript function that populates the value of the ASP textbox with ‘foo’.
The second button performs a post back that calls a method the does a ‘Response.Write’ to display the value of the text property of the ASP textbox.

protected void Go_Click(object sender, EventArgs e)
{
    Response.Write(string.Format("Returned Text: {0}", Target.Text));
}

No tricks.

When this code is run:

image_thumb1

Click “Populate TextBox”

image_thumb3

Click “Go!”

image_thumb7

Result

image_thumb9

There you have it!

 

Thanks for listening.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5