Search code examples
asp.netdrop-down-menuonchangeautopostback

ASP.NET 2.0: Calling a javascript function from onChange with AutoPostBack=true


I have an ASP.NET DDL that looks like this when I view source:

<select name="testControl" onchange="DoCustomStuff();setTimeout('__doPostBack(\'testControl\',\'\')', 0)" id="testControl">

It looks like this on the .cs page:

<asp:DropDownList ID="testControl" runat="server" onchange="DoCustomStuff()" OnSelectedIndexChanged="testControl_Changed" AutoPostBack="true" />

Can anyone see a problem with using onchange and AutoPostBack="true" on a DDL like this? I ask because we have some users for whom the DoCustomStuff() doesn't seem to be called correctly, and I'm wondering if it would be possible for the __doPostBack() to be executed before DoCustomStuff() completes its work.


Solution

  • Try to attach postback reference manually like that :

    Page.ClientScript.RegisterClientScriptBlock(
      typeof(_Default), 
      "PageScripts", 
      string.Format("function DoCustomStuff() { /* Your Code Here */ {0} }", Page.ClientScript.GetPostBackEventReference(testControl, string.Empty))
    );
    
    testControl.Attributes["onchange"] =  "DoCustomStuff();";
    

    this gives you the postback client side reference :

    Page.ClientScript.GetPostBackEventReference(testControl, string.Empty))