How do I read the SelectedValue of a DropDownList in code behind, when the option has been added using JavaScript?
A little more background: I have cascading drop down lists, and I would like to fill in the values using JavaScript, so that I avoid postbacks when the user changes the selection in the first drop down list.
I am not allowed to use an Update Panel.
I have build a simple demo demonstrating problem. Here is my markup code:
<p>
<asp:DropDownList runat="server" ID="FilterDropDownList" />
</p>
<p>
<asp:Button runat="server" ID="SearchButton" Text="Search"
onclick="SearchButton_Click" /><br/>
<asp:TextBox runat="server" ID="QueryTextBox" />
</p>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var filterDropDownListId = '#<%= FilterDropDownList.ClientID %>';
$(filterDropDownListId).append($('<option>').prop('value', 'Alpha').html('A'));
$(filterDropDownListId).append($('<option>').prop('value', 'Beta').html('B'));
});
</script>
And in the code behind I have the following:
protected override void Render(HtmlTextWriter writer)
{
// Register the allowed values for the down down list.
Page.ClientScript.RegisterForEventValidation(FilterDropDownList.UniqueID, "Alpha");
Page.ClientScript.RegisterForEventValidation(FilterDropDownList.UniqueID, "Beta");
base.Render(writer);
}
protected void SearchButton_Click(object sender, EventArgs e)
{
Response.Redirect(
String.Format("{0}?dropdown={1}&query={2}",
Request.Url.AbsolutePath,
FilterDropDownList.SelectedValue,
QueryTextBox.Text));
}
The problem is, that FilterDropDownList.SelectedValue is empty. I would have expected it to be either “Alpha” or “Beta”. I can read the value of QueryTextBox.Text without problems.
It is possible to read MyDropDownList.SelectedValue when the values have been populated using JavaScript? Or do a have to use a different approach?
You can always write the selected value to a hidden textbox with javascript and read the value in the code-behind.