Joseph Michael Pesch
VP Programming

Invalid postback or callback argument... Client side dynamic drop-down list values cannot be posted back to server

by 21. December 2010 11:39

If you attempt to change drop-down list options dynamically on the client side you may have issues with postback as the drop-down options will not match what the server originally sent to the client.  One way to overcome this is to have a server control with all the possible values (that is hidden on the UI) and a visible client side only drop-down list that is dynamically changed.  As the client side drop-down values are changed keep the server side control synchronized and then use the server side control value on post-back.  Simple sample below:

<%@ Page Language="C#" %>
 <script runat="server">
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)
    {
      this.ServerSelect.DataSource = new string[] { "one""two""three""four""five" };
      this.ServerSelect.DataBind();
    }
  }
  protected void SubmitButton_Click(object sender, EventArgs e)
  {
    this.ResultLabel.Text = string.Join(" ""You selected value:"this.ServerSelect.SelectedValue.ToString());
  }
</script>
<!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></title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function () {
      $.each(["one""two""three""four""five"], function (index, value) {
        $('select#LocalSelect').append($('<option></option>').val(value).html(value));
      });

      $('select#LocalSelect').change(function () {
        $('select#<%=ServerSelect.ClientID%>').val($('select#LocalSelect').val());
      });
    });
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:DropDownList ID="ServerSelect" runat="server" Style="display: none;" />
    <select id="LocalSelect">
    </select>
    <asp:Button ID="SubmitButton" Text="Submit" OnClick="SubmitButton_Click" runat="server" />
    <asp:Label ID="ResultLabel" runat="server" />
  </div>
  </form>
</body>
</html>

Tags:

Comments are closed