0

I have a custom control which inherits from TextBox. This allows me to use the TextBox's AutoPostBack property. This property makes the Page_Load method on the parent page fire when I change the value and click out of the text box. I am setting the value of the rendered text box in JS as follows

var outputData = document.getElementById("CameraScannerTextbox1");
outputData.value = barcode.Value;

When this code runs I am expecting the Page_Load method to run again. I have tried things like

outputData.focus();
outputData.value = barcode.Value;
outputData.blur();

The code in the Page_Load is

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        Label1.Text = CameraScannerTextbox1.Text;
    }
}

So basically I am hoping to have whatever is in barcode.Value set on Label1.Text on the server.

russelrillema
  • 452
  • 7
  • 14

2 Answers2

1

All you need is to trigger onchange event for input since ASP.NET adds postback code to onchange attribute. The simplest way is calling onchange manually

var outputData = document.getElementById("CameraScannerTextbox1");
outputData.value = barcode.Value;
outputData.onchange();

For more advanced techniques of simulating onchange event see this and this answers.

Alexander
  • 9,104
  • 1
  • 17
  • 41
0

You can simply trigger the PostBack yourself with __doPostBack.

<asp:TextBox ID="CameraScannerTextbox1" runat="server" ClientIDMode="Static" AutoPostBack="true"></asp:TextBox>

<asp:PlaceHolder ID="PlaceHolder1" runat="server">

    <script>
        var outputData = document.getElementById("CameraScannerTextbox1");
        outputData.value = '123456';
        __doPostBack('CameraScannerTextbox1', '');
    </script>

</asp:PlaceHolder>

Code behind

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        Label1.Text = CameraScannerTextbox1.Text;
        PlaceHolder1.Visible = false;
    }
}

Not that I placed the javascript in a PlaceHolder that is hiddedn on PostBack, otherwise it will create a PostBack loop. But there are other ways to prevent that also.

VDWWD
  • 35,079
  • 22
  • 62
  • 79