当使用JavaScript添加选项时,如何在后面的代码中读取DropDownList的SelectedValue?

时间:2011-11-14 19:22:10

标签: asp.net

当使用JavaScript添加选项时,如何在后面的代码中读取DropDownList的SelectedValue?

更多背景:我有级联下拉列表,我想使用JavaScript填写值,以便在用户更改第一个下拉列表中的选择时避免回发。

我不允许使用更新面板。

我已经构建了一个演示问题的简单演示。这是我的标记代码:

<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>

在后面的代码中我有以下内容:

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));
}

问题是,FilterDropDownList.SelectedValue为空。我原以为它应该是“Alpha”或“Beta”。我可以毫无问题地读取QueryTextBox.Text的值。

使用JavaScript填充值时,可以读取MyDropDownList.SelectedValue吗?或者必须使用不同的方法?

1 个答案:

答案 0 :(得分:1)

您始终可以使用javascript将所选值写入隐藏文本框,并在代码隐藏中读取值。