Saturday, December 22, 2012

Empty DropDownList.SelectedValue property when list is populated via javascript

In ASP.Net if you use DropDownList control on the page and populate it via javascript (using ClientID property of the list) you may face with the following problem: during the postback SelectedValue property will be empty. However if you will set it second time and make postback again, it will be set properly. It happens because when you first time fill the list on the client side, these values are not stored in the ViewState, so when list is populated with values from it, selected value becomes empty. Consider the following example:

   1: <%@ Page Language="C#" %>
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
   5: <html xmlns="">
   6: <head runat="server">
   7:     <title></title>
   8:     <script src="" type="text/javascript"></script>
  10:     <script type="text/javascript">
  11:         function populate() {
  12:             $("#<%= this.ddl.ClientID%>").append("<option value='1'>One</option>");
  13:             $("#<%= this.ddl.ClientID%>").append("<option value='2'>Two</option>");
  14:             $("#<%= this.ddl.ClientID%>").append("<option value='3'>Three</option>");
  15:         }
16: </script>
  17: </head>
  18: <body>
  19:     <form id="form1" runat="server">
  20:     <div>
  21:         <asp:DropDownList runat="server" ID="ddl" EnableViewState="False"/>
  22:         <br/>
  23:         <br/>
  24:         <button onclick="populate();return false;">Populate</button>
  25:         <br/>
  26:         <br/>
  27:         <asp:Button runat="server" ID="btn" Text="Postback"/>
  28:     </div>
  29:     </form>
  30: </body>
  31: </html>

If we will click Postback button, DropDownList.SelectedValue will be empty. Many forum threads mention that in order to solve it you need to add hidden field and synchronize your list with this field (save selected value when it is changed). However there is simpler way: instead of SelectedValue, use Request.Form[ddl.UniqueID]. It will contain correct selected value regardless of how it was populated.

No comments:

Post a Comment